Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get notified when a zeroing weak reference becomes nil on Objective-C under ARC?

Tags:

Is there a mechanism which would allow an object to know that a zeroing weak reference turned nil?

For example I have a property

@property (nonatomic, weak) MyClass *theObject; 

when theObject deallocates and the property turns nil I want to get notified. But how? Does the zeroing weak reference system use the setter to set the property to nil when the object goes away?

like image 742
openfrog Avatar asked Oct 13 '13 10:10

openfrog


People also ask

How do you find nil in Objective C?

Any message to nil will return a result which is the equivalent to 0 for the type requested. Since the 0 for a boolean is NO, that is the result. Show activity on this post. Hope it helps.

What is a weak reference Objective C?

Pointers that are not retained are often referred to as “weak” in Objective-C documentation that predates the garbage collector. These are references that are allowed to persist beyond the lifetime of the object. Unfortunately, there is no automatic way of telling whether they are still valid.


1 Answers

The runtime just sets the weak ivar _theObect to nil, a custom setter is not called.

What you could do (if you really need the notification):

  • define a local "watcher" class and implement dealloc in that class,
  • create a watcher object and set it as "associated object" of _theObject.

When _theObject is deallocated, the associated object is released and deallocated (if there are no other strong refereces to it). Therefore its dealloc method is called. This is your "notification".

(I'm writing this on the phone and can fill in the details later if necessary.)

like image 70
Martin R Avatar answered Sep 20 '22 18:09

Martin R