ios KVO 和 ARC 如何移除Observer
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6959896/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
KVO and ARC how to removeObserver
提问by drunknbass
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?
如何从ARC下的对象中删除观察者?我们是否只是添加了观察者而忘记删除它?如果我们不再手动管理内存,我们从哪里退出观察?
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.
以前,我会调用removeObserver:
视图控制器的dealloc
方法。
回答by Brad Larson
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.
您仍然可以-dealloc
在 ARC 下实现,这似乎是删除键值观察的合适位置。你只是不再[super dealloc]
从这个方法中调用了。
If you were overriding -release
before, you were doing things the wrong way.
如果您-release
之前进行了覆盖,那么您就是在以错误的方式做事。
回答by user3461902
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
}
}
回答by Elise van Looij
Elsewhereon 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.
在堆栈溢出的其他地方,Chris Hanson 建议为此目的使用 finalize 方法并实现单独的 invalidate 方法,以便所有者可以告诉对象它们已完成。过去,我发现 Hanson 的解决方案是经过深思熟虑的,所以我会继续这样做。