Search code examples
iosswiftnsnotificationcenter

Is removing observer obligatory (necessary)?


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?


Solution

  • 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.