实例已被解除分配,而关键价值观察员仍在其中注册 [英] Instance was deallocated while key value observers were still registered with it

查看:148
本文介绍了实例已被解除分配,而关键价值观察员仍在其中注册的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个UITableView。

I've got a UITableView.

这里我得到了不同的单元格。每个细胞都有一个模型。使用KVO和NotificationCenter,单元格会监听模型的更改。当我离开ViewController时,我收到此错误:

Here I got different cell's. Each cell has a model. With KVO and NotificationCenter the cell listen to the model for changes. When I leave the ViewController I get this error:

An instance 0x109564200 of class Model 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:
<NSKeyValueObservationInfo 0x109429cc0> (
<NSKeyValueObservance 0x109429c50: Observer: 0x10942d1c0, Key path: name, Options: <New: NO, Old: NO, Prior: NO> Context: 0x0, Property: 0x10968fa00>
)

在单元格中,我在设置/更改模型属性时执行此操作:

In the cell I do this when the model property is set/changed:

[_model addObserver:self
         forKeyPath:@"name"
            options:0
            context:nil];

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(modelIsInvalid:)
                                             name:@"modelIsInvalid"
                                           object:_model];

然后在单元格的dealloc中:

Then in the cell's dealloc:

- (void)dealloc
{
    NSLog(@"DEALLOC CELL");
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [_model removeObserver:self forKeyPath:@"name"];
}

在模型中我还检查它何时被解除分配:

In the model I also check when it get's deallocated:

- (void)dealloc
{
    NSLog(@"DEALLOC MODEL");
}

所有单元格在所有模型之前被释放,但我仍然收到此错误。此外,我不知道如何设置错误中提到的断点。

All cell's are deallocated before all the models, but still I get this error. Also I'm not sure how to set the breakpoint mentioned in the error.

推荐答案

它不起作用,因为单元格是被重用。因此,当单元格离开屏幕时,它不会被释放,它会重新使用池。

It won't work because the cells are being reused. So when the cell goes off the screen it's not deallocated, it goes to reuse pool.

您不应该在单元格中注册通知和KVO。您应该在表视图控制器中执行此操作,当模型更改时,您应该更新模型并重新加载可见单元格。

You shouldn't register notifications and KVO in cell. You should do it in table view controller instead and when the model changes you should update model and reload visible cells.

这篇关于实例已被解除分配,而关键价值观察员仍在其中注册的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆