Consider the following two allocations of arrays.
NSMutableArray* alpha = [[[NSMutableArray alloc] init] autorelease];
NSMutableArray* beta = [NSMutableArray array];
Assuming nothing else retains alpha or beta, my understanding is that the result of both is the same. The retain count on both will 0 and therefor they will be cleared up once they leave scope.
I have a sneaking suspision that I am not fully grasping the subtle implications between the two. After reading a StackOverflow answer I know the latter is a convenience method, but I would like to understand the differences.
What is the difference between the two lines of codes above in regards to memory management?
Those two lines are equivalent. In both cases objects are created that you have a reference to but not an owning reference. However, they’ll be on the autorelease pool. That means they’ll last as long as the pool does, which if you’ve not done anything special will be until control returns to the run loop. Objects like that therefore (usually) survive beyond their scope — that’s useful because it means you can (and usually do) provide autoreleased objects as return results.
The rule is that methods that return an object but do not contain ‘new’, ‘alloc’, ‘retain’ or ‘create’ in their name will return an autoreleased object. That’s the logic behind
+arrayreturning an autoreleased object.As an aside: if you enable ARC then autoreleased objects will still be returned but the compiler may be smart enough to take them out of the autorelease pool (which is something you can’t do manually) and release them manually in a calling method where it won’t affect program flow.