Pub-Sub Pattern in iOS

Bill Chee
2 min readNov 7, 2020

--

In this article, I would like to explore more on the pub-sub pattern in iOS swift development.

NSNotifcationCenter

The NSNoficationCenter in swift is the broker of the pub-sub pattern. It has a method call to add observers, and selectors to which the observer can subscribe to.

A Centralised Broker

Figure 1: High Level architecture for NSNotificationCenter

The broker role of the NSNotificationCenter can be illustrated via the diagram. The ViewController calls the NSNotificationCenter to subscribe to an event specified using a selector function. Changes to the data referenced by the selector will result in a notification to the ViewController via a method call.

Concrete Example

This section will provide a real-world example to illustrate this pattern.

NSNotificationCenter can be used for a login/logout feature where the authentication status of the user is an event to be subscribed to.

The home screen of the application subscribes to the authentication channel and checks if the user has been logged out for more than 12 hours, then a “welcome back” message will be displayed to the user. When the user is logged in, this login event is published to the broker, where the Home Screen, as an observer, receives this event via its subscription channel and checks if the condition is satisfied before responsively greeting the user.

Alternative to data binding: Delegate Pattern

In this section, we can analyse the pros and cons of the pub-sub pattern and how it compares to the delegate pattern.

One observer vs multiple observers

In the context of iOS development, NSNotificationCenter is used because an event that is emitted can be useful to a large number of observers. Broadcasting an event to multiple recipients is the main motivation for an NSNotificationCenter.

In the case of a delegate pattern, an event change invokes a single method call such as componentDidUpdate(), which notifies a single observer. This does not work well with multiple observers where code has to be extended to invoke delegate method calls for every single observer. As such, a NSNotificationCenter will be useful to reduce the complexity of the code.

Performance Comparison

If an event is called frequently, a delegate pattern will have better performance as compared to the pub-sub pattern. This is because the method call to the UIViewController is invoked directly by the delegate without having to publish the event first. As there is a slight performance cost, NSNotificationCenter should be avoided if there is only one consumer (or observer) consuming the notification.

Coupling

In terms of coupling involved, NSNotificationCenter has no coupling, which has an edge over the delegate pattern. The coupling that can be found in the delegate pattern depends on how generic the delegate protocol is defined. The less specific the blueprint is, the looser the coupling.

--

--