3

I'm reading an up-to-date book and ran across the ARC section. It explains these two ARC qualifiers:

Weak: Weak indicates that the object should not be retained (does not increase retain count). The compiler will set to nil before destruction.

__unsafe__unretained: Same as weak, but the object is not set to nil before it is destroyed.

My question is, why would it matter is the object is set to nil or not before it's destroyed? If the autorelease pool swings by and releases the destroyed object, it is no longer being used in memory. So, why would it matter if the object is set to nil before it's destroyed? The only case I would think of would be if it was a singleton...

Community
  • 1
  • 1
Henry F
  • 4,960
  • 11
  • 55
  • 98

2 Answers2

3

You ask:

My question is, why would it matter is the object is set to nil or not before it's destroyed?

It's not the "object" that is getting set to nil, but rather the weak variable referencing that object. Let's imagine that you have two references to some object, one strong and one weak. And let's assume you remove the strong reference (e.g. set that variable to nil). Now the object has no more strong references, it will therefore be deallocated. The beauty of weak references is that now that the object was deallocated, the weak reference will be set to nil, too, ensuring that you don't accidentally try to use that memory even though it has long since been deallocated and potentially reused for other purposes.

This contrasts with the assign or unsafe_unretained behavior: After the object is deallocated, if you had some other assign reference to it, that reference would be unchanged, pointing to memory that was freed (this is known as a "dangling pointer", pointing to something that isn't there any more).

Rob
  • 415,655
  • 72
  • 787
  • 1,044
2

From this SO answer:

__unsafe_unretained will continue pointing to the memory where an object was, even after it was deallocated. This can lead to crashes due to accessing that deallocated object.

You would always use weak because its much safer than __unsafe_unretained (hence the name). Also from the same thread:

__unsafe_unretained can be useful for defining C arrays of NSString constants and the like, e.g. NSString __unsafe_unretained *myStrings = { @"Foo", @"Bar", @"Baz", nil };

Community
  • 1
  • 1
Schemetrical
  • 5,506
  • 2
  • 26
  • 43