KVO and ARC how to removeObserver

IosCocoa TouchKey Value-ObservingAutomatic Ref-Counting

Ios Problem Overview


How do you remove an observer from an object under ARC? Do we just add the observer and forget about removing it? If we no longer manage memory manually where do we resign from observing?

For example, on a view controller:

[self.view addObserver:self
            forKeyPath:@"self.frame"
               options:NSKeyValueObservingOptionNew 
               context:nil];

Previously, I would call removeObserver: in the view controller's dealloc method.

Ios Solutions


Solution 1 - Ios

You still can implement -dealloc under ARC, which appears to be the appropriate place to remove the observation of key values. You just don't call [super dealloc] from within this method any more.

If you were overriding -release before, you were doing things the wrong way.

Solution 2 - Ios

I do it with this code

- (void)dealloc
{
@try{
    [self.uAvatarImage removeObserver:self forKeyPath:@"image" context:nil];
} @catch(id anException) {
    //do nothing, obviously it wasn't attached because an exception was thrown
}
}    

Solution 3 - Ios

Elsewhere on stack overflow, Chris Hanson advises using the finalize method for this purpose and implementing a separate invalidate method so that owners can tell objects that they are done. In the past I have found Hanson's solutions to be well-thought-out, so I'll be going with that.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiondrunknbassView Question on Stackoverflow
Solution 1 - IosBrad LarsonView Answer on Stackoverflow
Solution 2 - Iosuser3461902View Answer on Stackoverflow
Solution 3 - IosElise van LooijView Answer on Stackoverflow