Remove Observer issue in KVO in ios

2019-06-12 06:58发布

问题:

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

回答1:

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.