Starting with ios 9 it is not necessary to unsubscribe from notification center since ios handles this automatically, but prior to ios 9 developers had to manually call NotificationCenter.default.removeObserver(self)
in order to avoid memory leaks and common place for this was(it is suggested in a lot of tutorials and Stackoverflow posts) deinit
. So, my question is - how it was possible to use deinit
to unregister from notifications since deinit
is only called before objects deallocation, so its ref count should be 0, but for sure it is not - since we're still subscribe to the notification center. The only possible way to achieve this seems to be use of weak references, basically if notification center references object weakly the above mentioned scenario is possible, but in this case unsubscribing is not needed at all since the object can be easily deallocated. Can somebody clarify a bit on how this works.
NotificationCenter.default.removeObserver(self) in deinit, why deinit it even get called?
1.2k Views Asked by starwarrior8809 At
1
I think that prior to iOS9 NotificationCenter was adding observers as unretained pointers. Thus the point of removing observers in dealloc was not to prevent retain cycle but to prevent a crash when notification to released object could be sent.
From the iOS9 the NotificationCenter started using zeroing-weak referencing so it became possible to skip removing observers. You could find more details in the release notes: