Modern NSNotification Observers In Swift

The old way of handling notification observers looks something like this.

While this has worked since I started programming in 2009, the modern block syntax is better for a few reasons.

1. Does not rely on the “stringly” typed target selector method.

2. Better readability due to the block being right next to its caller.

This means you don’t have to worry about mistyping method selectors, and you see the action taken as a result of the notification being observed without having to search the file for it. The example from before would look like this.

However, instead of using self as the observer it returns an opaque object that conforms to NSObjectProtocol. This means when you remove observers you have to do so individually, or enumerate over a set to remove them all. I found myself doing this over and over again in deinit, so I looked into the problem and found an enlightening post on the topic. The post describes adding a wrapper around NSNotificationCenter. Genius!

Note: I have heard and seen arguments about ARC and not having to remove observers because NSNotificationCenter does not take ownership. However due to evidence of crashes being solved by removing observers it would be wise to do so regardless. And if you use a wrapper such as the one More Indirection uses ARC will in fact handle this for you.

Happy Coding

Recommend and follow me @iJoeCollins on Twitter.