문제

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)

도움이 되었습니까?

해결책

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.

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top