Is Removing a Notificationcenter Observer That Was Created with Closure Syntax by Name Adequate

Is removing a NotificationCenter observer that was created with closure syntax by name adequate?

You absolutely need to store the return value in a property and remove that later on.

From https://developer.apple.com/reference/foundation/nsnotificationcenter/1411723-addobserverforname:

Return Value


An opaque object to act as the observer.

When you call any one of the removeObserver methods, the first parameter is the observer to remove. When you set up a block to respond to a notification, self is not the observer, NSNotificationCenter creates its own observer object behind the scenes and returns it to you.

Note: as of iOS 9, you are no longer required to call removeObserver from dealloc/deinit, as that will happen automatically when the observer goes away. So, if you're only targeting iOS 9, this may all just work, but if you're not retaining the returned observer at all, the notification could be removed before you expect it to be. Better safe than sorry.

Where to remove observer for NSNotification in Swift?

Use below method which functions same as dealloc.

deinit {
// Release all resources
// perform the deinitialization
}

A deinitializer is called immediately before a class instance is deallocated. You write deinitializers with the deinit keyword, similar to how intializers are written with the init keyword. Deinitializers are only available on class types.

Swift Deinitializer

Extending NotificationCenter

It sounds like you need something like

extension NotificationCenter {
static func dispatch(key: String, payload: [String: String] = [:]) {
self.default.post(name: NSNotification.Name(rawValue: key), object: nil, userInfo: payload)
}
static func observe(key: String, handler: @escaping (Notification) -> Void) {
self.default.addObserver(forName: NSNotification.Name(rawValue: key), object: nil, queue: .main, using: handler)
}
}


Related Topics



Leave a reply



Submit