return statement inside nsautoreleasepool scope

二次信任 提交于 2019-12-11 17:18:05

问题


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?


回答1:


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];


来源:https://stackoverflow.com/questions/5083216/return-statement-inside-nsautoreleasepool-scope

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!