Ios – Objective-C autorelease memory management

cocoa-touchiosiphoneobjective c

Im trying to understand when to call autorelease, and what this will actually do to my object.

After reading About Memory Management in the Mac Developer Library I understood that when you have a method that acts as a factory method – by creating a new object and returning it – the method has no way of releasing the object before returning it, because this would result in a deallocted object being returned.

Example

- (Test *) createNewTest 
{
    Test *newInstance = [[Test alloc] init];
    [newInstance release];
    return newInstance; // deallocted object returned.
}

Instead I should use autorelease:

The autorelease method, defined by NSObject, marks the receiver for later release

My question is: if the object is to be released later, how do I know when its being released?

- (Test *) createNewTest 
{
    Test *newInstance = [[test alloc] init];
    [newInstance autorelease];
    return newInstance;
}

- (void) runIt
{
    Test *myInstance = [self createNewTest];
    // when is myInstance released?? and thereby not valid to my function anymore?
}

How can I safely use the returned autoreleased object inside my runIt method if I don't know when the autorelease happens? Should I retain the object returned by the createNewTest? Or can I safely use it within the runIt scope?

Best Answer

An autoreleased object is added to an autorelease pool.

Objects in the autorelease pool are released at the end of an iteration of the main runloop (or sooner if you are managing your own autorelease pool and/or if you call drain).

When you call a method that returns an autoreleased object, it is pretty much guaranteed to stay valid until at least the end of the scope that it was called in.

If you want to ensure that it stays alive longer then you should retain it, remembering to release it again when you're finished with it.