Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Want to perform action when __weak ivar is niled

I have a @class Foo which contains a __weak id bar ivar. Several actions from methods in different classes can cause the object to disappear and thus get bar niled.

I want to perform an action when the ivar is automatically niled by ARC.

If possible, I would want to avoid turning bar into a property or using Key-Value Observing.

Is this even possible? If not, can KVO be used against non-property ivars?

like image 670
Ricardo Sanchez-Saez Avatar asked Feb 19 '13 12:02

Ricardo Sanchez-Saez


Video Answer


2 Answers

I was led here by a duplicate question, here is what I answered:

You can't do that with KVO, but you can still get a notification and emulate this by associating an object with your iVar using objc_setAssociatedObject(), it will be deallocated when the 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 build on top of that very elaborate notifiers, using NSNotificationCenter or just custom blocks, depending on how heavily you rely on that for a specific ivar case or for lots of them.

The good thing about this solution is that it works with any __weak ivar, even if you don't control the type the __weak ivar has.

like image 120
JTAS Avatar answered Oct 21 '22 06:10

JTAS


KVO cannot be successfully used on non-property IVARs.

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

like image 30
Ricardo Sanchez-Saez Avatar answered Oct 21 '22 07:10

Ricardo Sanchez-Saez