简体   繁体   English

何时触发自动释放池

[英]When is the autorelease pool triggered

i have used autorelease throughout my app and would like to understand the behavior of the autorelease method. 我在我的应用程序中使用了自动释放,并希望了解自动释放方法的行为。 When is the default autorelease pool drained? 何时默认的自动释放池已耗尽? is it based on a timer (every 30sec?) or have to be called manually? 是基于计时器(每30秒?)还是必须手动调用? do I need to do anything to release variables that are flagged with autorelease? 我是否需要做任何事情来释放用自动释放标记的变量?

It is drained whenever the current run-loop finishes. 只要当前的运行循环结束,它就会耗尽。 That is when your method and the method calling your method and the method calling that method and so on is all done. 那是你的方法和方法调用你的方法和调用该方法等的方法都完成了。

From the documentation : 文档

The Application Kit creates an autorelease pool on the main thread at the beginning of every cycle of the event loop, and drains it at the end, thereby releasing any autoreleased objects generated while processing an event Application Kit在事件循环的每个循环开始时在主线程上创建一个自动释放池,并在最后将其排出,从而释放处理事件时生成的任何自动释放的对象

There are (I'd say) 3 main instances when they are created and release: 创建和发布时有(我会说)3个主要实例:

1.Beginning and very end of your application life-cycle, written in main.m 1.用main.m编写的应用程序生命周期的开始和结束

int main(int argc, char *argv[]) { 
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; 
    int retVal = UIApplicationMain(argc, argv, nil, nil); 
    [pool release]; 
    return retVal; 
}

2.Beginning and very end of each event (Done in the AppKit) 2.每个事件的开始和结束(在AppKit中完成)

NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; 
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil 
- (void)loadView 
/* etc etc initialization stuff... */
[pool release];

3.Whenever you want (you can create your own pool and release it. [from apples memory management document]) 3.无论何时你想要(你可以创建自己的池并释放它。[来自苹果内存管理文档])

– (id)findMatchingObject: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. */
}

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

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