views:

347

answers:

2

I am new to objective c and am trying to understand how/when autorelease is called. I understand the simple use case of:

- (void) foo {
    Bar *b = [[[Bar alloc] init] autorelease];
    [self doSomething:b];
  }

What about this next case -- is this a bug, because the object will be immediately released upon leaving the scope of makeBar?

-(Bar*) makeBar
{
    return [[[Bar alloc] init] autorelease];
}

What if the caller does a retain?

Bar *b = [[self makeBar] retain];

Thanks, -Eric

+4  A: 

In your second example, the anonymous object you're returning will not be released as soon as the execution leaves the scope of makeBar but on the next iteration of the run loop. This will give you the opportunity to retain it in whatever method has called makeBar

So your final example is ok since the retain count will not drop below 0.

Are you having trouble with it?

Tom Duckering
To be more specific, it will be released when the autorelease pool that it was added to is drained/released. This is typically at the end of a run loop, but not always.
dreamlax
No problems, I've just been scanning my code for potential memory issues and saw that pattern from sample code I had copied and wasn't sure if it was a bug or not.
esilver
+1  A: 
-(Bar*) makeBar
{
    return [[[Bar alloc] init] autorelease];
}

The 2nd case is the preferred way to return an Objective-C object. Except +alloc, -copy... and -create..., the method should retain no ownership of the returning object, i.e. the (change of) retain count should be 0.

However, [[Bar alloc] init] makes the object to have retainCount of +1, to one should release it before return. But -release will immediate deallocate the object, making the method useless. That's why -autorelease is used — it is a delayed -release, i.e. the object will be released eventually, but not now, so other parts of code can still interact with it, yet the retain count can still be balanced to 0.


Bar *b = [[self makeBar] retain];

You should not retain it unless you want to be a long-term owner of the object b.

KennyTM