ios - 为什么你必须在 ios8 中删除观察者?

标签 ios swift ios8 nsnotificationcenter

看完this发布 iOS 9,我知道你不再需要删除观察者了。

但是对于 iOS 8,您 needed removeObserver 在 vi​​ewController 的 deinit 方法中。 但我无法理解它。如果一个 viewController 被释放那么它就死了不是吗?为什么我们需要做一个 removeObserver。做一个旁观者就像调用一个永远不会接电话的死人

我不明白什么?

最佳答案

它在您链接的文章中有完整解释:

The notification center now keeps a zeroing reference to the observer:

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.

在 iOS 9 之前,NSNotificationCenter 不是使用 weak 引用实现的,因此 NSNotificationCenter 不知道目标已被释放。它盲目地向任何已注册的目标发送通知。如果目标已被解除分配,这很糟糕(可能会崩溃)。因此需要始终取消注册。

在 iOS 9 中,NSNotificationCenter 开始使用弱引用。这意味着它现在知道注册目标之一是否已被解除分配。这意味着它不再尝试向解除分配的目标发送通知。这意味着您不再需要在目标被解除分配之前显式注销目标。

关于ios - 为什么你必须在 ios8 中删除观察者?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39663984/

相关文章:

iOS Collection View结束检测和刷新

iOS 图片编辑开源库——或者只是一些小技巧

iphone - 构建时的InfoPlist.strings问题

ios - 来自另一个目标的 Swift 伞头

ios - RxSwift flatMapLatest 无需处理以前的可观察值

ios - 使用第二个 UIViewController 启动 ViewPagerController

ios - 如何创建带格式的字符串?

ios - 如何访问下载的解压文件夹中的图像?

ios - 将标签快速调整为 slider 值

swift - CLAuthorizationStatus AuthorizedWhenInUse 仅在第一次调用