Want to perform action when __weak ivar is niled

寵の児 提交于 2019-12-01 16:54:36

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.

KVO cannot be successfully used on non-property IVARs.

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

I suggest to override dealloc. If you know the type of the object that will be allocated, and it's a custom class (otherwise subclass it), you can perform the action when the object is deallocated, which is exactly what happens when ARC sets the retain count to zero and sets the weak variable to nil.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!