简体   繁体   中英

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.

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

I tried setting a breakpoint using NSKVODeallocateBreak, and what I observed is that it stops that the line @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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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