我有一个模型对象,一个直接的 NSObject 子类,其属性由使用 KVO 的上下文对象观察。
我在模型对象的 dealloc 中从 KVO 取消注册,如下所示:
- (void) dealloc
{
[self.context unregisterObject:self];
}
上下文的方法如下所示:
- (void) unregisterObject:(MyCustomObject*) inObject
{
for (NSString *property in [inObject propertyNamesToObserve])
{
[inObject removeObserver:self forKeyPath:property context:(void*)kCustomContext];
}
}
我仍然从运行时收到一条消息,如下所示,所以我想知道 -dealloc 是否太晚而无法从 KVO 取消注册?
An instance 0x10045fc10 of class MyCustomObject was deallocated while key value observers were still registered with it. Observation info was leaked, and may even become mistakenly attached to some other object. Set a breakpoint on NSKVODeallocateBreak to stop here in the debugger. Here's the current observation info:
根据这篇文章,我正在做的事情应该没问题: KVO and ARC how to removeObserver
或者我忽略了什么?我检查了调用 dealloc 时上下文是否为非零。
最佳答案
想通了。模型对象由上下文为 KVO 注册了两次,但仅取消注册了一次。
关于objective-c - -dealloc 对于从 KVO 取消注册来说太晚了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16179465/