Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

KVO and ARC how to removeObserver

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.

like image 758
drunknbass Avatar asked Aug 05 '11 16:08

drunknbass


2 Answers

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.

like image 73
Brad Larson Avatar answered Oct 22 '22 06:10

Brad Larson


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 } }     
like image 24
user3461902 Avatar answered Oct 22 '22 07:10

user3461902