Why does it matter if the object is destroyed on destruction?

I am reading the latest book and running through the ARC section. He explains these two ARC qualifiers:

Weak : Weak indicates that the object should not be persisted (does not increase the hold count). The compiler will set to nil before destructing.

__ unsafe__unretained : same as weak, but object is not set to zero until destroyed.

My question is, why does it matter if the object is set to zero or not, before it is destroyed? If the autoresist pool swings and frees the destroyed object, it is no longer used in memory. So why does it matter if the object is set to zero before being destroyed? The only case I would think of would be if it was a single ...

+3


source to share


2 answers


You're asking:

My question is, why does it matter if the object is set to zero or not, before it is destroyed?



It is not an "object" that receives a value nil

, but rather a variable weak

that refers to that object. Imagine that you have two references to some object: one strong

and one weak

. And suppose you remove the link strong

(for example, set this variable to nil

). Now the object has no stronger references, so it will be deallocated. The beauty of referencing weak

is that now that the object has been freed, a weak referencing will be set to nil

too, ensuring that you don't accidentally try to use that memory, even if it's been freed a long time ago and potentially reusable for other purposes.

This contrasts with the behavior of assign

or unsafe_unretained

: after the object is freed, if you have some other reference assign

, that reference will not change, pointing to the freed memory (this is known as a "dangling pointer" pointing to something that no longer exists).

+3


source


From this SO answer:

__ unsafe_unretained will continue to point to memory where the object was, even after it has been freed. This can lead to crashes due to access to this freed object.



You will always use weak because it is much safer than __unsafe_unretained (hence the name). Also from the same topic:

__ unsafe_unretained can be useful for defining C arrays of NSString constants, etc. NSString __unsafe_unretained * myStrings = {@ "Foo", @ "Bar", @ "Baz", nil};

+2


source







All Articles