Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should a self-implemented getter retain and autorelease the returned object?

Example:

- (NSString*) title {
    return [[title retain] autorelease];
}

The setter actually retained it already, right? and actually nobody should bypass the Setter... so I wonder why the getter not just returns the object? It's actually retained already. Or would this just be needed in case that in the mean time another objects gets passed to the setter?

like image 728
Thanks Avatar asked Apr 29 '09 10:04

Thanks


1 Answers

From here http://www.macosxguru.net/article.php?story=20030713184140267

- (id)getMyInstance
    {
        return myInstanceVar ;
    }

or

- (id)getMyInstance
{
    return [[myInstanceVar retain] autorelease] ;
}

What's the difference ? The second one allows the caller to get an instance variable of a container object, dispose of the container and continue to play with the instance variable until the next release of the current autoreleased pool, without being hurt by the release of the instance variable indirectly generated by the release of its container:

aLocalVar = [aContainer getAnInstanceVar] ;
[aContainer release];
doSomething(aLocalVar);

If the "get" is implemented in the first form, you should write:

aLocalVar = [[aContainer getAnInstanceVar] retain];
[aContainer release];
doSomething(aLocalVar);
[aLovalVar release];

The first form is a little bit more efficent in term of code execution speed. However, if you are writing frameworks to be used by others, maybe the second version should be recommanded: it makes life a little bit easier to people using your framework: they don't have to think too much about what they are doing…;) If you choose the first style version, state it clearly in your documentation… Whatever way you will be choosing, remember that changing from version 1 to version 2 is save for client code, when going back from version 2 to version 1 will break existing client code…

like image 59
oxigen Avatar answered Oct 23 '22 05:10

oxigen