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? swift swift

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.


To add to @Dave's answer, it looks like documentation isn't always 100% accurate. According to this article by Ole Begemann there is a contradiction in the doc and self-removing magic was not happening as of iOS 11.2 in his test app.

So that the answer is still "Yes, one needs to remove that observer manually" (and yes, self is not the observer, the result of addObserver() method is the observer).


Here an example with code, for how a correct implementation looks like:

Declare the variable that gets returned when you add the observer in your class A (the receiver of the notification or observer):

private var fetchTripsNotification: NSObjectProtocol?

In your init method add yourself as an observer:

init() {    fetchTripsNotification = NotificationCenter.default.addObserver(forName: .needsToFetchTrips, object: nil, queue: nil) { [weak self] _ in        guard let `self` = self else {            return        }        self.fetchTrips()    }}

In the deinit method of your class, make sure to remove the observer:

deinit { NotificationCenter.default.removeObserver(fetchTripsNotification as Any) }

In your class B (the poster of the notification) trigger the notification like usually:

NotificationCenter.default.post(name: .needsToFetchTrips, object: nil)