使用KVO时,是否有必要在-dealloc中删除self作为self的观察者? [英] When using KVO is it necessary to remove self as an observer of self in -dealloc?

查看:254
本文介绍了使用KVO时,是否有必要在-dealloc中删除self作为self的观察者?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的NSObject子类的-init方法中,该实例将自己添加为自己的某些keyPath的观察者,以触发在有问题的属性之一发生更改时应发生的操作.例如.

in my NSObject subclass's -init method the instance adds itself as an observer of some of its own keyPaths in order to trigger an action that should occur any time one of the properties in question is changed. eg.

[self addObserver:self forKeyPath:@"aProperty" options:0 context:nil];
[self addObserver:self forKeyPath:@"anotherProperty" options:0 context:nil];
...

我的问题是,在类的-dealloc方法中,我是否必须删除实例作为自身的观察者?例如.

My question is, in the class's -dealloc method do I necessarily need to remove the instance as an observer of itself? eg.

[self removeObserver:self forKeyPath:@"aProperty"];
[self removeObserver:self forKeyPath:@"anotherProperty"];
...

我认为,当对象试图向不存在的对象发送消息时,就会引发异常,这显然是一个问题.但是在这种情况下,不再存在的对象不可能向自身发送消息,因此这不应该成为问题.

The way I figure it, when an object tries to send a message to an object that no long exists then an exception gets thrown, clearly a problem. But in this case, an object that doesn't exist anymore couldn't possibly send messages to itself, so this shouldn't be a problem.

我对此还没有任何问题,但是它仍然让我感到困扰,因为我从未见过它明确表明您可以这样做.

I haven't had any issues with this yet, but it does still kind of bother me since I've never seen it explicitly stated that you can do this.

我只是想避免写一大堆

[self removeObserver:self forKeyPath ...]

在我的-dealloc方法中.

in my -dealloc method.

推荐答案

您可能会在不删除self作为观察者的情况下逃脱现实,但您不应该这样做.在执行addObserver:...的位置,您还必须稍后再执行removeObserver:....

You probably could get away without removing self as an observer, but you shouldn’t. Where you do addObserver:... you also have to do removeObserver:... later.

但是无论如何,此讨论是无关紧要的,因为无需遵守self,只需在属性设置器中触发您的操作即可.这样可以使代码更清晰,可读性更强,而实际上执行得更好.

But this discussion is irrelevant anyways, because there is no need to observe self, just trigger your action in the setter of your property. This leads to clearer, more readable code that actually performs better.

这篇关于使用KVO时,是否有必要在-dealloc中删除self作为self的观察者?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆