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

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

问题描述

据我所知,使用alloc副本创建的任何内容都需要手动释放.例如:

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 发送到对象时,都会将其添加到最内部的自动释放池中.当池被排空时,它只是向池中的所有对象发送 -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天全站免登陆