Tuesday, January 9, 2018

Unregistering Block-based NotificationCenter Observers

Ole Begemann:

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 capture self in your observer block. If you do, your deinit will never get called because the block retains self (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.

Comments RSS · Twitter

Leave a Comment