删除观察者是强制性的(必要的)吗? [英] Is removing observer obligatory (necessary)?

查看:60
本文介绍了删除观察者是强制性的(必要的)吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个观察者,我在整个应用程序生命周期中都需要它,我应该删除它吗?我认为 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 及更早版本的支持.您必须删除 deallocviewWillDisappear 中的观察者.可以在此处找到更详细的答案.

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 将不再向可能被释放的注册观察者.如果观察者能够存储为弱置零引用,底层存储将将观察者存储为归零弱引用,或者如果对象不能弱存储(即它具有自定义的保留/释放阻止运行时能够存储弱对象)它将对象存储为非弱归零参考.这意味着观察者不需要取消注册在他们的解除分配方法中.

In OS X 10.11 and iOS 9.0 NSNotificationCenter and NSDistributedNotificationCenter will no longer send notifications to registered observers that may be deallocated. If the observer is able to be stored as a zeroing-weak reference the underlying storage will store the observer as a zeroing weak reference, alternatively if the object cannot be stored weakly (i.e. it has a custom retain/release mechanism that would prevent the runtime from being able to store the object weakly) it will store the object as a non-weak zeroing reference. This means that observers are not required to un-register in their deallocation method.

更详细的解释可以在这里.

注意:但是在使用上面链接的文档中提到的基于块的通知时要小心.

Note: However be careful when using block-based notifications as mentioned in the doc linked above.

这篇关于删除观察者是强制性的(必要的)吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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