Best Place to Remove NotificationCenter Observer in Swift Struct

Viewed 1243

Say we have a given Swift class.

class Test {
    init() {
        NotificationCenter.default.addObserver( ... ) 
    }

    deinit {
        NotificationCenter.default.removeObserver(self)
    }
}

In a class, you can use the deinit lifecycle method to remove the NotificationCenter observer. In a struct, there is no deinit method. My question is therefore, where would someone remove the NotificationCenter observer in a struct? Or possibly, do we not have to remove the observer in a struct?

2 Answers

From iOS 9 and above, it's not necessary to remove NotificationCenter observers as they are automatically removed.

If you are concerned about observes stuck in memory anyway, you should call the removal from a class that is handling the struct.

You can't register a struct as an observer in the NotificationCenter. When you use the addObserver(_:selector:name:object:) method you have to pass the Selector as a parameter. The selector must be a function marked with @objc and you can use it only with classes.

When it comes to the classes you can unregister an observer in the deinit method as you mentioned in the question. However, you don't have to remove observers manually since iOS 9 because since this release NSNotificationCenter stores weak references to the observers. Removing of the observers is not done automatically for you.

According to the release notes.

NSNotificationCenter and NSDistributedNotificationCenter 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 stores the observer as a zeroing weak reference. Alternatively, if the object cannot be stored weakly (because it has a custom retain/release mechanism that would prevent the runtime from being able to store the object weakly) the object is stored as a non-weak zeroing reference. This means that observers are not required to un-register in their deallocation method.

Related