简体   繁体   English

在iOS中消除KVO中的Observer问题

[英]Remove Observer issue in KVO in ios

I have a table which is filled with an array of objects, which I am observing, and when I delete all the objects, I remove the observer , but the problem is that when I delete all the objects in array and then again start adding it to the array I get removeObserver issue. 我有一个表格,里面充满了要观察的对象数组,删除所有对象时,我删除了观察者,但是问题是当我删除数组中的所有对象然后再次开始添加时,问题是到阵列我得到removeObserver问题。

I have a strong reference to my object 我对我的对象有很深的了解

I am adding Observer this way 我这样添加观察者

[self.object addObserver:self forKeyPath:kTaskCompletedKey options:NSKeyValueObservingOptionNew context:&kTaskObservationContext];

and I am removing it this way 我以这种方式将其删除

- (void)dealloc;
{
    [self.object removeObserver:self forKeyPath:kTaskCompletedKey context:&kTaskObservationContext];    
}

and also when I delete the object in the table using the delete method 以及当我使用delete方法删除表中的对象时

I tried setting a breakpoint using NSKVODeallocateBreak, and what I observed is that it stops that the line @sythesize object = m_object; 我尝试使用NSKVODeallocateBreak设置断点,观察到的是它停止了@sythesize object = m_object;这一行@sythesize object = m_object; and I dont understand what that means So, friends please help me out 我不明白这意味着什么,所以朋友们请帮帮我

Regards Ranjit 问候兰吉特

You must remove the observation before deleting the object. 您必须先删除观测值,然后再删除对象。 After doing that there is some debugging message you can send the object that let's you log the current observers - send it then verify no observers. 完成此操作后,您会收到一些调试消息,您可以发送该对象,让您记录当前的观察者-发送该对象,然后验证没有观察者。 Then you can safely release the objects. 然后,您可以安全地释放对象。

EDIT: if the object you are observing, you can add the log in its dealloced - it had better report no observers. 编辑:如果您正在观察的对象,则可以将日志添加到已取消分配的对象中-最好不要报告观察者。 So, add this to the dealloc of your observed object: 因此,将其添加到观察对象的dealloc中:

NSLog(@"Dealloc of %@ with observationInfo: %@", self, [self observationInfo]);

In your controller, just before you release the observed object (which I assume is done by removing it from the array), use this log: 在您的控制器中,就在释放观察到的对象(我假设是通过将其从数组中删除完成)之前,使用以下日志:

id foo = [myArray objectAtIndex:whatever];
NSLog(@"Release %@ with observationInfo: %@", foo, [foo observationInfo]);

If you find you are releasing an object you are still observing, that's a problem. 如果发现释放的对象仍在观察中,那就是一个问题。 If an object is getting dealloced and its still being observed that's a problem too. 如果一个对象被释放并且仍然被观察到,那也是一个问题。

EDIT: Before you add an object to the array, test if its already there or not. 编辑:在将对象添加到数组之前,测试其是否已经存在。 If not, then observe it. 如果没有,请观察。 If yes, then you know you already are observing it. 如果是,则表明您已经在观察它。

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

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