SundayMonday
SundayMonday

Reputation: 19747

Objective-C runtime and memory management

While looking for an NSStack or similar I came across this code sample. In the pop method the author explicitly retains returnObject and then returns an autorelease object. Is this really necessary? I'm under the impression that the runtime will destroy the object removed from contents via removeLastObject at the end of a run-loop iteration (and not somewhere in the middle).

Upvotes: 4

Views: 143

Answers (1)

Caleb
Caleb

Reputation: 125007

Is this really necessary?

It is if you're still using manual memory management. Without that retain, returnObject could be deallocated as soon as you remove it from the array. A mutable array retains the objects that it contains and releases them upon removal. Retaining an object before removing it prevents the object from being deallocated; autoreleasing it allows the object to stick around long enough for the calling method to receive it.

If you're using ARC (and there aren't many reasons not to), you don't have to worry about any of that. The compiler will figure out when to retain and when to release for you.

I'm under the impression that the runtime will destroy the object removed from contents via removeLastObject at the end of a run-loop iteration

That's what would happen if NSMutableArray autoreleased objects when it removes them, but I don't see any reason to think that it does. You could count on the removed object being autoreleased if -removeLastObject returned the removed object, but it doesn't. You should never make assumptions about what another object does with the objects it owns.

Upvotes: 6

Related Questions