繁体   English   中英

在dealloc之前观察并删除类别中的NSNotification

[英]Observe and remove an NSNotification within a category before dealloc

我目前正在观察一个类别中对象的整个生命周期的通知。 但是,我正在调动dealloc方法以获得删除观察的位置。 这感觉不好,我对它感到不舒服,另外我遇到了问题。

有没有人有任何想法如何在一个类别中取消分配对象之前停止观察通知?

在释放无法覆盖dealloc的对象时运行代码的最佳方法是使用关联对象

与其关联的对象将在取消分配时释放其强关联对象。 只要那是唯一的所有者,就会调用关联对象的dealloc 使用您为关联对象控制的类,这是您的入口点。

我有一个演示,使用这个技巧在GitHub回购中取消注册KVO https://github.com/woolsweater/UIViewController-WSSDataBindings

控制器将辅助对象与自身关联:

- (void)WSSBind:(NSString *)bindingName
   toObject:(id)target
withKeyPath:(NSString *)path
{
    WSSBinding * binding = [WSSBinding bindingWithBoundName:bindingName
                                                   onObject:self
                                                  toKeyPath:path
                                                   ofObject:target];

    // Attach the binding to both target and controller, but only make it
    // owned by the target. This provides automatic deregistration when the
    // target is destroyed, and allows the controller to unbind at will.
    // Disregard the target and bound path for the key to allow mirroring
    // Cocoa's unbind: method; this is simplest for the controller.
    NSUInteger key = [self WSSAssociateKeyForBinding:bindingName];
    objc_setAssociatedObject(target, (void *)key, binding,
                             OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    objc_setAssociatedObject(self, (void *)key, binding,
                             OBJC_ASSOCIATION_ASSIGN);
}

并且WSSBinding类实现dealloc以移除在其他地方设置的观察者。 您可以为NSNotification注册执行相同的操作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM