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