Is cleaning up strong references in deinit a correct pattern?

前提是你 提交于 2019-12-04 21:14:30

This statement

[...] that recommend removing an observer from the NotificationCenter in the deinit of the UIViewController [...]

was true in the past.

And your statement

[...] if there still is a strong reference to the class, deinit will not get called.

is correct.

Observers have weak reference

An observer holds a weak reference to the target object.

This explain why the deinit of an object will be called even if there are multiple active observers.

So why do we want to remove the observers in the deinit?

This was needed prior to iOS 9 to prevent an observer from invoking a method of a deallocated object.

However unregistering an observer is no longer needed from macOS 10.11 and iOS 9.0

In OS X 10.11 and iOS 9.0 NSNotificationCenter and NSDistributedNotificationCenter will no longer send notifications to registered observers that may be deallocated.

Source

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!