nsautoreleasepool 范围内的 return 语句

发布于 2024-10-18 15:27:20 字数 528 浏览 3 评论 0原文

假设我有以下场景:

- (void)someFunction:(id)param {

    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    NSObject *objectA = [[NSObject alloc] init];
    [objectA doStuff];  // Don't need to release objectA because of the pool

    if (!someValue) {
        [pool release];   // Doubt here
        return;
    }

    NSObject *objectB = [[NSObject alloc] init];
    [objectB doStuff];  // Don't need to release objectB because of the pool

    [pool release];
}

以这种方式从池块内部返回是否正确?

Lets say I have the below scenario:

- (void)someFunction:(id)param {

    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    NSObject *objectA = [[NSObject alloc] init];
    [objectA doStuff];  // Don't need to release objectA because of the pool

    if (!someValue) {
        [pool release];   // Doubt here
        return;
    }

    NSObject *objectB = [[NSObject alloc] init];
    [objectB doStuff];  // Don't need to release objectB because of the pool

    [pool release];
}

Is it right to return from inside the pool block in this way?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

南街女流氓 2024-10-25 15:27:20

简短的回答:是的。

长答案:没有显式释放而被放弃的池在其嵌套的自动释放池(通常是当前线程的顶部自动释放池)被释放时被释放。

顺便说一句,这是错误的:

NSObject *objectA = [[NSObject alloc] init];
[objectA doStuff];  // Don't need to release objectA because of the pool

您仍然必须显式地释放分配的对象:

NSObject *objectA = [[NSObject alloc] init];
[objectA doStuff];
[objectA release];

或者通过将它们添加到自动释放池中:


NSObject *objectA = [[[NSObject alloc] init] autorelease];
[objectA doStuff];

Short answer: yes.

Long answer: pool that is abandoned without explicit release is released when the autorelease pool in which it nests (usually current thread's top autorelease pool) is released.

Btw, this is wrong:

NSObject *objectA = [[NSObject alloc] init];
[objectA doStuff];  // Don't need to release objectA because of the pool

You still have to release allocated objects, either explicitly:

NSObject *objectA = [[NSObject alloc] init];
[objectA doStuff];
[objectA release];

or by adding them to autorelease pool:


NSObject *objectA = [[[NSObject alloc] init] autorelease];
[objectA doStuff];
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文