Objective-C runtime and memory management

If you are looking for NSStack or the like, I came across this sample code . In the pop method, the author explicitly stores returnObject , and then returns an autorelease object. Is it really necessary? I get the impression that the runtime will destroy the object removed from the contents via removeLastObject at the end of the iteration of the run loop (and not somewhere in between).

+4
source share
1 answer

Is it really necessary?

This is if you are still using manual memory management. Without this, returnObject can be freed as soon as you remove it from the array. The modified array saves the objects that it contains and frees them when deleted. Saving an object before deleting it prevents the object from being freed; auto-implementation allows the object to linger long enough for the caller to receive it.

If you use ARC (and not many reasons), you have nothing to worry about. The compiler will determine when to save and when to release for you.

I get the impression that the runtime will destroy the object removed from the contents via removeLastObject at the end of the iteration run loop

What happens if NSMutableArray becomes auto-implemented objects when it is deleted, but I see no reason to think that it is. You can expect the remote object to be auto-implemented if -removeLastObject returned the remote object, but that is not the case. You should never make assumptions about what another object is doing with the objects that it owns.

+6
source

Source: https://habr.com/ru/post/1440428/


All Articles