我目前正在观察 类别 中对象的整个生命周期中的通知。但是,我正在调整 dealloc 方法以有一个位置来删除观察。这感觉很糟糕,我对此感到不舒服,而且我遇到了问题。
有没有人知道如何在对象将被释放到类别之前停止观察通知?
最佳答案
在无法重写dealloc
的对象的释放时运行代码的最佳方法是使用associated objects。 .
您关联的对象将在解除分配时释放其强持有的关联对象。只要它是唯一的所有者,关联对象的 dealloc
就会被调用。使用您控制关联对象的类,这是您的入口点。
我在 GitHub 存储库中演示了如何使用此技巧注销 KVO https://github.com/woolsweater/UIViewController-WSSDataBindings
Controller 将辅助对象关联到自身:
- (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
注册做同样的事情。
关于ios - 在 dealloc 之前观察并删除类别中的 NSNotification,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31600067/