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…
Let’s assume
topwould look like this:Then imagine this:
The following would happen: The second line would make the retain count drop to 0, and by the third line
foowould point to deallocated memory. But with theretainandautoreleasethe retain count is 1, until the pool is emptied thus on the third linefoowould still point to a valid object.