为什么你要删除ios8中的观察者? [英] why do you have to remove observer in ios8?

查看:132
本文介绍了为什么你要删除ios8中的观察者?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在阅读iOS 9的帖子后,我知道你不再需要删除Observer。

After reading this post for iOS 9, I know that you don't need to removeObserver anymore.

然而对于iOS 8,你需要 removeObserver deinit viewController的方法。
但我无法理解它。如果一个viewController被释放,那么它的DEAD不是吗?为什么我们需要做一个removeObserver。它是一个观察者就像打电话给一个永远不会拿起电话的死人一样

However for iOS 8, you needed to removeObserver in the deinit method of the viewController. But I can't make sense of it. If a viewController is deallocated then it's DEAD isn't? Why do we need to do a removeObserver. It being an observer is much like calling a dead person who will never pick up the phone

我不理解什么?

推荐答案

您在链接的文章中对此进行了详细解释:

It's fully explained in the article you linked:


通知中心现在保留对观察者的归零引用:

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 未使用引用所以 NSNotificationCenter 不知道目标已被解除分配。它盲目地向任何已注册的目标发送通知。如果目标已被解除分配,这很糟糕(可能会崩溃)。因此需要始终取消注册。

Prior to iOS 9, NSNotificationCenter wasn't implemented using a weak reference so NSNotificationCenter didn't know the target had been deallocated. It blindly sent notifications to any target that had been registered. This is bad (likely crash) if the target has been deallocated. Hence the need to always unregister.

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

In iOS 9, NSNotificationCenter started using weak references. This means it now knows if one of the registered targets has been deallocated or not. This means it no longer attempts to send notifications to deallocated targets. And this means you no longer need to explicitly unregister the target before it is deallocated.

这篇关于为什么你要删除ios8中的观察者?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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