ios - 注销后,我得到 "class deallocated while key value observers were still registered with it"

标签 ios objective-c key-value-observing

我有一些适用于许多对象的代码,将我的类注册为 KVO:

for (SPPanelManager *manager in self.panelManagers) {
    [manager addObserver:self forKeyPath:@"dataFetchComplete" options:0 context:NULL];
    [manager fetchData];
}

然后当它观察到发生在每个这些对象上的变化时,我取消注册:

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if ([keyPath isEqualToString:@"dataFetchComplete"] && ((SPPanelManager *)object).dataFetchComplete) {
        [object removeObserver:self forKeyPath:@"dataFetchComplete"];

        //Other stuff
    }
}

然后当我稍后离开 UIViewController 时,每个管理器对象都会出现以下错误:

An instance of class 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.

我不确定为什么它会给我这个错误 - 这是唯一引用 KVO 的 2 个地方,所以它不是另一个观察者。

最佳答案

您的类(class)(观察者)正在某些事件期间被释放。您必须在它被解除分配或不再被进一步使用之前注销它。在 viewDidUnload:dealloc:

中使用下面的代码
for (SPPanelManager *manager in self.panelManagers) {
    [manager removeObserver:self forKeyPath:@"dataFetchComplete" context:NULL];
  }

关于ios - 注销后,我得到 "class deallocated while key value observers were still registered with it",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17454241/

相关文章:

ios - 如何以编程方式使用自动布局排列这三个 UILabel?

iphone - 打字时键盘挡住屏幕

objective-c - 显示图像的 cocoa 问题

ios - 独立跟踪下载进度UI

ios - 如果使用 KVO 的特定对象如何观察属性变化?

ios - 使用单例作为数据管理器类不好吗?

iphone - 我如何在导航 Controller 中弹出

ios - Swift Mapkit View 中心

objective-c - 使用 KVO 更新由 NSPredicate 过滤的 NSTableView

ios - 库未加载 : @rpath/AWSCore. 框架/AWSCore... 在运行应用程序时显示此错误