在 Cocoa 中,我是否需要在取消分配对象时从接收 KVO 通知中删除它? [英] In Cocoa do I need to remove an Object from receiving KVO notifications when deallocating it?

查看:20
本文介绍了在 Cocoa 中,我是否需要在取消分配对象时从接收 KVO 通知中删除它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我注册一个对象 foo 以接收来自另一个对象 bar 的 KVO 通知时(使用 addObserver:...),如果我然后解除分配 foo 我是否需要在 -dealloc 中向 bar 发送 removeObserver:forKeyPath: 消息?

When I've registered an object foo to receive KVO notifications from another object bar (using addObserver:...), if I then deallocate foo do I need to send a removeObserver:forKeyPath: message to bar in -dealloc?

推荐答案

-[NSObject dealloc]之前需要使用-removeObserver:forKeyPath:去除观察者运行,所以是的,在您的类的 -dealloc 方法中执行它会起作用.

You need to use -removeObserver:forKeyPath: to remove the observer before -[NSObject dealloc] runs, so yes, doing it in the -dealloc method of your class would work.

比这更好的是有一个确定性的点,在这个点上,任何拥有进行观察的对象都可以告诉它它已经完成并且将(最终)被释放.这样,当不再需要执行观察的事物时,您可以立即停止观察,而不管它何时实际释放.

Better than that though would be to have a deterministic point where whatever owns the object that's doing the observing could tell it it's done and will (eventually) be deallocated. That way, you can stop observing immediately when the thing doing the observing is no longer needed, regardless of when it's actually deallocated.

记住这一点很重要,因为 Cocoa 中对象的生命周期并不像某些人认为的那样具有确定性.各种 Mac OS X 框架本身发送您的对象 -retain-autorelease,从而延长它们的生命周期,超出您的想象.

This is important to keep in mind because the lifetime of objects in Cocoa isn't as deterministic as some people seem to think it is. The various Mac OS X frameworks themselves will send your objects -retain and -autorelease, extending their lifetime beyond what you might otherwise think it would be.

此外,当您过渡到 Objective-C 垃圾收集时,您会发现 -finalize-dealloc 将在非常不同的时间和非常不同的上下文中运行 做到了.一方面,终结发生在不同的线程上,因此您确实不能安全地将 -removeObserver:forKeyPath: 发送到 -finalize<中的另一个对象/code> 方法.

Furthermore, when you make the transition to Objective-C garbage collection, you'll find that -finalize will run at very different times — and in very different contexts — than -dealloc did. For one thing, finalization takes place on a different thread, so you really can't safely send -removeObserver:forKeyPath: to another object in a -finalize method.

-dealloc-finalize 中坚持内存(和其他稀缺资源)管理,并使用单独的-invalidate 方法来拥有所有者在确定的时间点告诉对象您已经完成了它;做一些事情,比如在那里删除 KVO 观察.您的代码意图将更加清晰,您需要处理的细微错误将更少.

Stick to memory (and other scarce resource) management in -dealloc and -finalize, and use a separate -invalidate method to have an owner tell an object you're done with it at a deterministic point; do things like removing KVO observations there. The intent of your code will be clearer and you will have fewer subtle bugs to take care of.

这篇关于在 Cocoa 中,我是否需要在取消分配对象时从接收 KVO 通知中删除它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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