NSAutoreleasePool自动释放池如何工作? [英] How does the NSAutoreleasePool autorelease pool work?

查看:71
本文介绍了NSAutoreleasePool自动释放池如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我了解,使用分配副本创建的所有内容都需要手动发布.例如:

As I understand it, anything created with an alloc, new, or copy needs to be manually released. For example:

int main(void) {
    NSString *string;
    string = [[NSString alloc] init];
    /* use the string */
    [string release];
}

不过,我的问题是不是一样有效?:

My question, though, is wouldn't this be just as valid?:

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

推荐答案

是的,您的第二个代码段是完全有效的.

Yes, your second code snippit is perfectly valid.

每次-autorelease发送到一个对象时,它就会被添加到最里面的autorelease池中.当池耗尽时,它只是向池中的所有对象发送-release.

Every time -autorelease is sent to an object, it is added to the inner-most autorelease pool. When the pool is drained, it simply sends -release to all the objects in the pool.

自动释放池只是一种便利,它使您可以将发送-release推迟到以后".这种后期"可能会在多个地方发生,但是在Cocoa GUI应用程序中最常见的是在当前运行循环周期结束时.

Autorelease pools are simply a convenience that allows you to defer sending -release until "later". That "later" can happen in several places, but the most common in Cocoa GUI apps is at the end of the current run loop cycle.

这篇关于NSAutoreleasePool自动释放池如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆