Unregistering Block-based NotificationCenter Observers
Yes, you still have to unregister block-based observations manually (as of iOS 11.2). The documentation for
removeObserver(_:)
is at least misleading if not wrong.[…]
When you do the unregistering in
deinit
, you must make sure not to captureself
in your observer block. If you do, yourdeinit
will never get called because the block retainsself
(preventing its destruction) and the notification center holds a strong reference to the block. Your object will live forever.[…]
I suggest you write a small wrapper class for the observation token the notification center returns to you. The wrapper object stores the token and waits to be deallocated. Its only task is to call
removeObserver(_:)
in its own deinitializer[…]
Previously: NSNotificationCenter With Blocks Considered Harmful.