简体   繁体   English

如何在Objective-C中处理自动释放池中的对象?

[英]How objects in Autorelease pools are handled in Objective-C?

My question is when a object is actually added to autorelease pool? 我的问题是何时将对象实际添加到自动释放池? When a Autorelease pool is created and objects are declared within the scope, are they added in autorelease pool or they are added in pool when specified as autoreleased. 创建自动释放池并在范围内声明对象时,将它们添加到自动释放池中,或者在指定为自动释放时将它们添加到池中。

int main(void) { 
    NSAutoreleasePool *pool; 
    pool = [[NSAutoreleasePool alloc] init]; 
    NSString *string; 
    NSArray * array;
    string = [[[NSString alloc] init] autorelease]; 
    array = [[NSArray alloc] init];
    /* use the string */ 
    [pool drain]; 
} 

In this case is only string is added to pool or even array is added to pool? 在这种情况下,仅将字符串添加到池中,还是将数组添加到池中?

Objects are added to autorelease pools (yes, pools, there's a stack of them per thread) when -autorelease is called on them, and only then. 在对象上调用-autorelease时,才将对象添加到自动释放池中(是的,每个线程有一个堆栈)。 However, in methods that don't contain the words 'new', 'alloc', or 'copy' (more or less, I might be forgetting one or two), the returned value is usually autoreleased for you, before it is returned. 但是,在不包含单词“ new”,“ alloc”或“ copy”(或多或少,我可能会忘记一两个)的方法中,返回值通常在返回之前自动为您释放。 You should really read the memory management guide in full (it's not that painful). 你真的应该阅读内存管理指南全(它不是那么痛苦)。

Objects are added to the autorelease pool only when they are sent the autorelease method. 当对象被发送自动释放方法时,它们才被添加到自动释放池。

Autorelease pools stack and the object is added only to the topmost pool (most recently created) in the stack at the time the object is sent autorelease. 自动释放池堆栈,并且在对象被发送自动释放时,该对象仅添加到堆栈中最顶层的池(最近创建的池)中。

However, autorelease pools themselves are effectively in the next pool down the stack. 但是,自动释放池本身实际上位于堆栈中的下一个池中。 Thus if you drain the oldest pool, all the pools created since then will also be drained. 因此,如果您清空最旧的池,则此后创建的所有池也将被清空。 This is important in the context of throwing exceptions. 这对于抛出异常非常重要。 It makes it possible to throw an exception through a stack frame with an autorelease pool in it without leaking the pool or the objects in it. 这样就可以通过其中具有自动释放池的堆栈框架引发异常,而不会泄漏池或其中的对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM