问题描述
有几种资源(,,加上我看到它在任何地方使用)建议从的
,例如: deinit
中的 NotificationCenter
中删除观察者UIViewController
There are several resources (blog, SO question, plus I've seen it used everywhere) that recommend removing an observer from the NotificationCenter
in the deinit
of the UIViewController
, e.g.:
deinit {
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
现在根据我不必关心从 NotificationCenter 因为它使用了弱
引用,我看到了与其他引用一样的模式。
Now while according to another blog entry I don't have to care about removing an observer from NotificationCenter
since it uses weak
references, I've seen the same pattern used with other references.
这个问题让我烦恼。根据官方:
The question that bugs me. According to official documentation:
这是否意味着如果仍然有强烈的类引用, deinit
不会被调用,因此呈现 deinit
引用清理无用?如果 NotificationCenter
中仍然存在对 viewController
的强引用,则 viewController
的 deinit
永远不会被调用,对吗?因此,删除 deinit
中强大的refenreces永远不会真正起作用。
Doesn't this mean that if there still is a strong reference to the class, deinit
will not get called, thus rendering the deinit
references cleanup useless? If there is still a strong reference to the viewController
from the NotificationCenter
, then viewController
's deinit
will never get called, right? So removing the strong refenreces in deinit
can never really work.
我在这里遗漏了什么吗?
Am I missing something here?
推荐答案
此声明
的deinit中从NotificationCenter中删除观察者过去是真的。
was true in the past.
您的陈述
是正确的。
观察者持有弱引用
到目标对象。
An observer holds a weak reference
to the target object.
这解释了为什么即使有多个活跃的观察者也会调用一个对象的 deinit
。
This explain why the deinit
of an object will be called even if there are multiple active observers.
这是必需的 iOS 9之前,以防止观察者调用解除分配对象的方法。
This was needed prior to iOS 9 to prevent an observer from invoking a method of a deallocated object.
然而,不再需要从macOS 10.11取消注册观察者iOS 9.0
However unregistering an observer is no longer needed from macOS 10.11 and iOS 9.0
这篇关于在清除正确的模式中清理强引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!