看完this发布 iOS 9,我知道你不再需要删除观察者了。
但是对于 iOS 8,您 needed removeObserver 在 viewController 的 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/