Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is return autorelease a bug in objective c?

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

like image 697
esilver Avatar asked Feb 17 '10 16:02

esilver


2 Answers

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?

like image 82
Tom Duckering Avatar answered Nov 04 '22 09:11

Tom Duckering


-(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.

like image 41
kennytm Avatar answered Nov 04 '22 11:11

kennytm