Question

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

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top