The CocoaTouch UI framework has its own built-in implementation of the Mediator design pattern, named NSNotificationCenter. You can use an instance of the NSNotificationCenter class to broadcast notifications to any objects that are interested in that particular event. Several components in CocoaTouch use this mechanism, such as how MPMoviePlayerController sends out notifications when a movie starts and stops.
To a .NET developer this might seem like a strange and inconvenient way to raise and handle an event on an object. In one sense, that is true. Since Objective-C does not have first-class support for constrained multicast delegates (i.e. events) like most .NET languages, you can instead use NSNotificationCenter to publish something to other entities, pass related arguments, and a include back pointer to the object that published the notification. Sounds like events, right?
To a certain extent that is true. However, NSNotificationCenter is not a substitute for events. It is an implementation of the Mediator design pattern, much like the Messenger class in my MVVM Foundation library (used by WPF developers). It provides an externalized event source, which helps reduce coupling between publisher objects and subscriber objects.
The difference between .NET events and a Mediator, regardless of the platform, is that an event can only be raised by the object that owns the event. This requires all subscribers to reference the event publisher object, thus increasing the system’s self-awareness. I don’t mean to imply that .NET events are a bad thing, but in some situations simpler designs can be achieved by using a third party to broker events between parties.
Enough pontification, now let’s look at an example of using this cool class. First let’s declare the name of a custom notification and the name of the dictionary entry that stores the ‘message’ argument passed to the notification recipients.
Now we will head over to the implementation file and define those values…
Obviously the value of those strings don’t matter, so long as they’re unique within the scope of my application. Technically it is not necessary to take the extra step of defining these string identifiers in a separate file, you could just hard-code the values into your methods, repeating the values wherever needed. But that would make the person who maintains your code want to viciously murder you in your sleep.
Next let’s see how to send out a notification using NSNotificationCenter.
Last but not least, the subscriber code.
That’s all for this post.