Objective-c – Object instance memory management

cocoaobjective c

This is a follow on from another question, my question is regarding the use of the retain/release in main(). From my understanding in this simple example the retain/release statements are not needed. BUT in more complex situations its best practice to add them as it ensures that the planet instance is not released unexpectedly.

+(Planet *) planet {
    gPlanetCount++;
    //return [[[Planet alloc] init] autorelease];
    return [[[self alloc] init] autorelease];     // Better
}

int main(int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    Planet *outerMost;

    outerMost = [[Planet planet] retain];
    ...
    ... some code
    ...
    [outerMost release]; 
    [pool drain];
    return 0;
}

EDIT_001

So I could better write the above as.

int main(int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    Planet *outerMost;

    outerMost = [Planet planet];
    ...
    ... some code
    ...
    [pool drain];
    return 0;
}

cheers gary

Best Answer

Markus Müller's comment is correct, that is, your code is correct, except for the missing pool allocation and initialization.

However, if you create an autoreleased object in a routine/method, and you use that object in that routine/method, and you are done with it, before you exit that routine/method, then there is no reason to retain it and then release it. That object is guaranteed to be retained for the duration of the life of the routine/method, and, in this case, it will most likely be released by the [pool drain] method.

You are not going to have a situation where outerMost is released unexpectedly. The expected release is in [pool drain]. It doesn't matter how many other methods are called from within main(), as long as you are sicking to the retain/release guidelines, outerMost will not need to be retained.

Related Topic