Is removing observer obligatory (necessary)?

梦想与她 提交于 2019-12-12 17:24:44

问题


There is an observer that I need it in all of app life cycle, shall I ever remove it? I think GC will remove it after app is closed, am I right? If yes, then when shall I remove it? in deinit?


回答1:


If you are providing support to iOS 8 and before. You will have to remove the observer inside dealloc or viewWillDisappear. A more detailed answer can be found here.

If you are providing support from iOS 9 onwards, it is no longer necessary to manually remove the observer. From apple docs:

In OS X 10.11 and iOS 9.0 NSNotificationCenter and NSDistributedNotificationCenter will no longer send notifications to registered observers that may be deallocated. 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. This means that observers are not required to un-register in their deallocation method.

A more detailed explanation can be found here.

Note: However be careful when using block-based notifications as mentioned in the doc linked above.



来源:https://stackoverflow.com/questions/41689506/is-removing-observer-obligatory-necessary

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