-->

iOS的自动释放池块(iOS autorelease pool blocks)

2019-09-01 02:11发布

我是从苹果阅读文档内存管理,当我到自动释放池块和东西让我思考。

 Any object sent an autorelease message inside the autorelease pool block is  
 released at the end of the block.

我不知道我完全理解这一点。 自动释放池块中创建的任何对象在得到反正块月底发布,因为这是它的寿命。 为什么你需要自动释放调用对象当它迟早要释放时到达块的结束?

为了更清楚,我会给出我在想什么的例子,:

   @autoreleasepool {

    MyObject *obj = [[MyObject alloc] init]; // no autorelease call here

    /* use the object*/
   //....
   // in the end it should get deallocated because it's lifespan ends, right?
   // so why do we need to call autorelease then?!
  }

PS:请不要告诉我,因为ARC的我们并不需要做一些事情,因为ARC照顾他们。 我充分意识到这一点,但我要离开ARC预留了短短的几分钟,了解内存管理机制。

Answer 1:

自动释放只是去除它没有“自由”的记忆立刻类似于C的对象保留计数。 当自动释放池结束与计数0所有自动释放对象将有自己的内存释放出来。

有时你创建大量的对象。 一个例子是,每次是创建新的字符串进行迭代,并增加了新的数据字符串循环。 你可能不需要串的早期版本和将要释放那些使用的内存。 您可以通过显式使用自动释放池,而不是等待它自然做做到这一点。

//Note: answers are psudocode

//Non Arc Env
@autoreleasepool 
{

    MyObject *obj = [[MyObject alloc] init]; // no autorelease call here
    //Since MyObject is never released its a leak even when the pool exits

}
//Non Arc Env
@autoreleasepool 
{

    MyObject *obj = [[[MyObject alloc] init] autorelease]; 
    //Memory is freed once the block ends

}
// Arc Env
@autoreleasepool 
{

    MyObject *obj = [[MyObject alloc] init]; 
    //No need to do anything once the obj variable is out of scope there are no strong pointers so the memory will free

}

// Arc Env
MyObject *obj //strong pointer from elsewhere in scope
@autoreleasepool 
{

    obj = [[MyObject alloc] init]; 
    //Not freed still has a strong pointer 

}


Answer 2:

(大多只是提供了一些额外的背景; @ Kibitz503越来越您正确的答案。)

@autoreleasepool {

  MyObject *obj = [[MyObject alloc] init]; // no autorelease call here

  /* use the object*/
  //....
  // in the end it should get deallocated because it's lifespan ends, right?
  // so why do we need to call autorelease then?!
}

PS:请不要告诉我,因为ARC的我们并不需要做一些事情,因为ARC照顾他们。 我充分意识到这一点,但我要离开ARC预留了短短的几分钟,了解内存管理机制。

好吧,让我们不考虑ARC。 在上面的,没有ARC, obj不会被释放。 只是因为ARC增加了额外的release电话并可能得到释放(给你的例子,我们其实不知道,因为我们不知道会发生什么use the object )。

正如@ Kibitz503解释说,“释放”并不意味着“解除分配”。 在块中,自动释放池排水管,这意味着任何未决的端autorelease呼叫被作为发送release在块的末尾。 如果导致到达0保留计数的对象,然后将其释放。

但无论上述是在一个块中或没有,没有ARC它是一个泄漏。



Answer 3:

自动释放池推迟到达结束前被释放的对象,直到它避免它的可能性池结束的释放。 所以基本上,它是确保对象将不会游泳池的年底之前发布。



文章来源: iOS autorelease pool blocks