问题描述
有一个观察者,我在整个应用程序生命周期中都需要它,我应该删除它吗?我认为 GC
会在应用关闭后删除它,对吗?如果是,那我什么时候删除它?在 deinit
?
There is an observer that I need it in all of app life cycle, shall I ever remove it?I think GC
will remove it after app is closed, am I right?If yes, then when shall I remove it? in deinit
?
推荐答案
如果您提供对 iOS 8 及更早版本的支持.您必须删除 dealloc
或 viewWillDisappear
中的观察者.可以在此处找到更详细的答案.
If you are providing support to iOS 8 and before. You will have to remove the observer inside dealloc
or viewWillDisappear
. A more detailed answer can be found here.
如果您从 iOS 9 开始提供支持,则不再需要手动移除观察者.来自苹果文档:
If you are providing support from iOS 9 onwards, it is no longer necessary to manually remove the observer. From apple docs:
在 OS X 10.11 和 iOS 9.0 NSNotificationCenter 和NSDistributedNotificationCenter 将不再向可能被释放的注册观察者.如果观察者能够存储为弱置零引用,底层存储将将观察者存储为归零弱引用,或者如果对象不能弱存储(即它具有自定义的保留/释放阻止运行时能够存储弱对象)它将对象存储为非弱归零参考.这意味着观察者不需要取消注册在他们的解除分配方法中.
更详细的解释可以在这里.
注意:但是在使用上面链接的文档中提到的基于块的通知时要小心.
Note: However be careful when using block-based notifications as mentioned in the doc linked above.
这篇关于删除观察者是强制性的(必要的)吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!