Want to complete an action when __weak ivar niled

I have @class Foo that contains __weak id bar ivar. Several actions from methods in different classes can lead to the disappearance of the object and, thus, get bar niled.

I want to perform an action when ivar is automatically painted over by ARC.

If possible, I would like not to turn bar into a property or use monitoring for key values.

Is it possible? If not, can KVO be used against non-invariant ivars?

+6
objective-c automatic-ref-counting ivar
source share
3 answers

KVO cannot be successfully used on non-property IVARs.

You cannot detect from the runtime when Objective-C ARC nils IVAR.

+2
source share

I was brought here on the second question, this is what I answered:

You cannot do this with KVO, but you can still get notified and emulate it by associating an object with your iVar using objc_setAssociatedObject() , it will be freed when a weak variable dies.

 @interface WeakObjectDeathNotifier : NSObject @end @implementation WeakObjectDeathNotifier - (void)dealloc { // the code that shall fire when the property will be set to nil } @end 

You can create on top of these very well-designed notifications using NSNotificationCenter or just custom blocks, depending on how much you rely on it for a particular ivar case or for many of them.

Well, this solution is that it works with any __weak ivar, even if you do not control the __weak ivar type.

+4
source share

I suggest redefining dealloc. If you know the type of object to be allocated, and this is a user class (otherwise its subclass), you can perform the action when the object is freed, which happens when ARC sets the hold value to zero and sets the weak variable to zero.

0
source share

All Articles