iOS NotificationCenter in a better way

A common pattern in app development is notifications (NSNotification and NotificationCenter). With notifications you can broadcast out messages to multiple listeners. This can be useful in many cases. A common example is if you have many UIViewControllers that all need to update on some model change.

However, I feel that the standard way of using NotificationCenter is error prone, complicated and verbose. I mostly use another approach, where you create your own version of NotificationCenter.

The normal way

First, an example on normal use of NotificationCenter:

Here we just use the standard APIs. We add an extension to Notification.Name for a bit smoother setup. But other that that, this is the default way to broadcast notifications. What I don’t like about this approach:

  • We use string literals. It feels old, bad and error prone.
  • We cast userInfo. The receiver needs to know the type of the payload. If we need to send more parameters we need to have more casting or string constants as keys.
  • The addObserver function is quite long and needs to be repeated for each listener.
  • We have to come up with names for the string literal, notification name variable and the callback method.

A better way?

The solution is quite straight forward. We create one optional func in our protocol for each type of notification. And we also create one function that broadcasts to all delegates.

NotificationManager is then stored in whatever place you prefer. If you want it as a singleton it can be done, but I prefer to have it as an instance somewhere.

And in Weak.swift we define a container for weak references. This is needed as normal arrays hold a strong reference to it’s elements.

And here is how you use NotificationManager:

As you can see, the setup becomes so much cleaner, one row for adding self as delegate, and one for removing. Then you extend your class and implement the optional functions of the NotificationDelegate protocol you want to listen to. That means that even if you listen to several notification you still need only that addDelegate one-liner as a setup!

The broadcasting becomes quite clean as well:

Here you can setup parameters in any way you want, no more casting from userInfo.

To summarize:

  • No more string literals
  • No more casting, we can pass along multiple typed parameters
  • The addDelegate function is super short and is only needed once per class
  • We still need to come up with two names, for the callback function and the corresponding function in NotificationManager, but I usually use the same

Hope you liked the solution. Let me know what you think in the comments. Can this perhaps be improved even further?