KVO 和 ARC 如何删除观察者

如何从 ARC下的对象中移除观察者?我们是不是只要加上观察者,就不用移除它了?如果我们不再手动管理内存,我们在哪里放弃观察?

例如,在视图控制器上:

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

以前,我会在视图控制器的 dealloc方法中调用 removeObserver:

20333 次浏览

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.

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.

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
}
}