Saran Saran - 6 months ago 14
Swift Question

Does ARC set its reference type instance properties to nil before deallocation?

This question occured to me while reading this.

My question is in reference to the image below:

enter image description here

Once john is set to nil,

Person
instance no longer has any more strong reference and hence will be deallocated. But
Apartment
has two strong references and one of which is by the property on
Person
instance that would be soon deallocated. I believe, this strong reference continue to remain after deallocation and goes out of reach by the code.

So, setting
unit14A
to
nil
will remove only one strong reference to
Apartment
instance and it should not be deallocated as there would be one more strong reference due to the above case.

But, as the document says
Apartment
instance promptly got deallocated. To me, this can only happen if at the time of
Person
instance deallocation it sets its apartment property to
nil
, by that removing that strong reference on
Apartment
instance. But I couldn't find any documentation to verify this.

So, How does the Apartment instance get deallocated? What happened to the strong reference from the Person instance apartment property?

Can someone help me to understand this?

CRD CRD
Answer

Your intuition is correct. When an object is being deallocated under ARC all the strong references it holds are first relinquished - essentially they are set to nil, but in practice the implementation may differ.

This is also what happens when a method returns, or a block of code containing declarations exits, all the strong references held in local variables are relinquished.

All the details can be found in the Clang documentation.

HTH

Comments