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

Dan Beaulieu picture Dan Beaulieu · Jan 29, 2017 · Viewed 8.2k times · Source

I have a few notifications that were created using block / trailing closure syntax which look like this:

NotificationCenter.default.addObserver(forName: .NSManagedObjectContextObjectsDidChange, object: moc, queue: nil) { note in
    // implementation
}

Which I was later removing by name, like this:

NotificationCenter.default.removeObserver(self, name: NSNotification.Name.NSManagedObjectContextObjectsDidChange, object: moc)

My Question

Is this adequate? Or do I absolutely need to save the NSObjectProtocol to it's own property and remove that property with the following syntax?

NotificationCenter.default.removeObserver(didChangeNotification)

Answer

Dave Weston picture Dave Weston · Jan 29, 2017

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.