Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the point in a retain immediately followed by an autorelease?

I'm looking at some open source code and trying to understand why the author has done something in a particular way.

The class is a wrapper around NSArray to create a stack data structure with push, pop, etc.

One method is topObject which returns the topmost object on the stack and its implementation is:

- (id)top {
    return [[[stack lastObject] retain] autorelease]; // stack is an instance of NSMutableArray
}

What's with the retain followed by an immediate autorelease?

My initial reaction was that this would prevent an analyser warning about a memory leak, but I analysed without the retain/autorelease and there was still no warning.

Looking at the lifecycle, an object would be created, pushed to the stack and released, so the stack owns the object (the underlying array will retain it upon adding).

So I don't understand the use of the retain/autorelease here...

like image 390
Jasarien Avatar asked Oct 15 '10 14:10

Jasarien


1 Answers

Let's assume top would look like this:

- (id) top {
    return [stack lastObject];
}

Then imagine this:

foo = [bar top];
[bar removeAllObjects];
// Do something with foo

The following would happen: The second line would make the retain count drop to 0, and by the third line foo would point to deallocated memory. But with the retain and autorelease the retain count is 1, until the pool is emptied thus on the third line foo would still point to a valid object.

like image 51
DarkDust Avatar answered Oct 20 '22 03:10

DarkDust