Question

Let's say I have a 2 classes, classes A and B. By composition, Class A has an instance of Class B. In other words, Class A is the one creating the instance of Class B.

If I'm in the final release of my object which is a kind of class A, will the dealloc method of Class B be executed first? Is this always the case? Will there be a case where the dealloc of Class A will be executed before Class B?

I'm trying to understand the order in which the dealloc method of classes will be executed.

(This is in ARC)

Was it helpful?

Solution

If you delete (or, in real terms, remove the last strong reference to) the instance of class A, it will be deallocated. Under ARC, as part of its deallocation, it will remove its strong reference to the instance of class B, which will then be deallocated if nothing else has a strong reference to it.

So, A's dealloc method is called first.

If you're depending on this order of operations to do anything, that is a pretty bad code smell.

OTHER TIPS

When the last strong reference to a given object goes away, its -dealloc will run, and it will remove all of its strong references to its instance variables. If those were the last strong references to those objects, then the process will repeat for them.

In other words, if A owns B, then A will be deallocated before B.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top