在清除正确的模式中清理强引用? [英] Is cleaning up strong references in deinit a correct pattern?
问题描述
有几种资源( blog , SO问题,加上我看到它在任何地方使用)建议从的
,例如: 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)
}
现在根据另一篇博客文章我不必关心从<删除观察者code> 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:
在取消分配类实例之前立即调用deinitializer。您使用deinit关键字编写deinitializers,类似于使用init关键字编写初始化程序的方式。 Deinitializers只适用于班级类型。
A deinitializer is called immediately before a class instance is deallocated. You write deinitializers with the deinit keyword, similar to how initializers are written with the init keyword. Deinitializers are only available on class types.
这是否意味着如果仍然有强烈的类引用, 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?
推荐答案
此声明
[...]建议在UIViewController [...]
[...] that recommend removing an observer from the NotificationCenter in the deinit of the UIViewController [...]
的deinit中从NotificationCenter中删除观察者过去是真的。
was true in the past.
您的陈述
[...]如果仍有强大的参考到了上课,deinit将不会被调用。
[...] if there still is a strong reference to the class, deinit will not get called.
是正确的。
观察者持有弱引用
到目标对象。
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.
这是必需的
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
在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.
这篇关于在清除正确的模式中清理强引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!