开发者

return statement inside nsautoreleasepool scope

开发者 https://www.devze.com 2023-02-12 11:12 出处:网络
Lets say I have the below scenario: - (void)someFunction:(id)param { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

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开发者_JAVA技巧

    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?


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号