我是否必须手动删除KVO中的Observer

我是否必须手动删除KVO中的Observer

本文介绍了我是否必须手动删除KVO中的Observer的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读了苹果文档

I have read the apple document about KVO, and it said:

观察者对象没有对观察对象的强引用.

The observer object not have a strong references to the observered object.

这个人我不能在dealloc方法中调用removeObserver:forKeyPath:吗?它可以自动删除观察者吗?

Does this man I can not call removeObserver:forKeyPath: in the dealloc method? Can it remove the observer automatically?

推荐答案

您必须手动调用-removeObserver:forKeyPath:. iOS不会自动执行此操作.

You must call -removeObserver:forKeyPath: manaully. iOS will not do it automatically.

Apple说 does not maintain strong references to the observing object .我认为这意味着,如果要为超出temp var范围的temp var移除RemoveObserver,则应将temp var设为ivar,以便维护ivar的强引用.

Apple said does not maintain strong references to the observing object. I think it means, if you want to removeObserver for a temp var out off the temp var's scope, you should make the temp var as ivar, so you maintain the ivar's strong references.

如果您不拨打-removeObserver:forKeyPath:.您将做出以下操作:1)东西泄漏

If you do not call -removeObserver:forKeyPath:. You will make : 1) Something leak

例如您这样的代码:

[self addObserver:a forKeyPath:@"name" options:NSKeyValueObservingOptionNew context:nil];

(如果您不呼叫-removeObserver:forKeyPath:).它将控制台:

if you do not call -removeObserver:forKeyPath:. It will console that :

An instance 0x756a1d0 of class MyClass was deallocated while key value observers were still registered with it. Observation info was

泄漏,甚至可能错误地附着在其他物体上. 在NSKVODeallocateBreak上设置一个断点以在调试器中停止. 这是当前的观察信息: [NSKeyValueObservationInfo 0x7574f60]( [NSKeyValueObservance 0x7574f20:观察者:0x7568280,键路径:pageCount,选项:[新:是,旧:否,优先:否]上下文:0x0, 属性:0x7574fa0] )

leaked, and may even become mistakenly attached to some other object. Set a breakpoint on NSKVODeallocateBreak to stop here in the debugger. Here's the current observation info: [NSKeyValueObservationInfo 0x7574f60] ( [NSKeyValueObservance 0x7574f20: Observer: 0x7568280, Key path: pageCount, Options: [New: YES, Old: NO, Prior: NO] Context: 0x0, Property: 0x7574fa0] )

调试时,您会发现:selfa没有泄漏.泄漏的是NSKeyValueObservationInfo object

When you debug it, you will find : The self and the a are not leaking. The leaking thing is the NSKeyValueObservationInfo object

如果您不拨打-removeObserver:forKeyPath:.您将获得:2)中级课程永远不会破坏&&无限通知

If you do not call -removeObserver:forKeyPath:. You will make : 2) Intermediate class never destroy && Infinity notification

正如苹果公司有关KVO的文件所述:

As the Apple document about KVO says:

当您删除Observer时,如果未注册任何观察者,则中间类将销毁.而且,如果不调用removeObserver,则中间类将永远不会销毁,并且当您更改属性时,中间类的setter方法将继续发送通知.

When you removeObserver, if no observer is registered, the intermediate class will destroy. And If you not call removeObserver, the intermediate class will never destroy and when you change the property, the setter method of intermediate class will continue to send notifications.

这篇关于我是否必须手动删除KVO中的Observer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!