autorelease什么时候真的会在Cocoa Touch中导致发布?
  我知道你需要小心iOS上的autorelease 。  我有一个返回一个对象时,它的方法alloc是由主叫方需要S,所以在这种情况下-我的理解是-我需要发送autorelease的对象在被调用它返回之前。 
这很好,但一旦控制权返回到手机(即我的按钮点击处理后)似乎释放了自动释放池。 我怀疑这应该是怎么回事,但我想知道这种情况的最佳做法是什么。
  我采取了从调用者发送retain消息,以便该对象不被释放,然后在dealloc明确释放它。 
这是最好的方法吗?
自动释放池通常在运行循环的每次迭代后释放。 粗略地说,每个Cocoa和Cocoa Touch应用程序都是这样构成的:
Get the next message out of the queue
Create an autorelease pool
Dispatch the message (this is where your application does its work)
Drain the autorelease pool
你描述的是预期的行为。 如果你想保持一个对象的时间不止于此,你需要明确地保留它。
  使用autorelease是一种说法,“对象,我不再需要你了,但我会把你转给别人,他们可能需要你,所以不要消失。”  因此,对象将保持足够长的时间,以便您从方法返回它或将其提供给另一个对象。  当某些代码想要保留该对象时,它必须通过retain它来声明所有权。 
  有关正确使用autorelease需要知道的所有内容,请参阅内存管理指南。 
这是Apple Memory Management文档中提供的一个例子:
– (id)findMatchingObject:(id)anObject 
{ 
    id match = nil; 
    while (match == nil) { 
        NSAutoreleasePool *subPool = [[NSAutoreleasePool alloc] init]; 
        /* Do a search that creates a lot of temporary objects. */ 
        match = [self expensiveSearchForObject:anObject]; 
        if (match != nil) { 
            [match retain]; /* Keep match around. */ 
        } 
        [subPool release]; 
    } 
    return [match autorelease];   /* Let match go and return it. */ 
}
上一篇: When does autorelease actually cause a release in Cocoa Touch?
