Broadcasting with NSNotification Center

Jen Sipila
iOS App Development

--

NSNotification is an apple class that allows for messages to be sent out over all classes in a project and to be heard or received from anywhere, to anyone listening.

Establishing a notification is simple. Call the following method when you want a notification message to be deployed. (It can be especially useful in a completion block to announce when an action has been completed to a class outside the immediate scope of the method.)

The NSString notification name will be sent out and any NSNotification observers with the same string will receive the notification.

The “listener” for the notification can be set up anywhere in any method or class by initializing a default NSNotificationCenter, like this:

In the above example this receiver method call listens for “SomeActionIsComplete” sent by the calling of an NSNotification method somewhere else in the code.

When it hears the call it will NSLog a message and dismiss the view controller class that contains it.

Passing an object with the notification

If you want to pass more than just a message when sending out the notification you can do so by using the userInfo: argument on the method.

The userInfo argument should be given an NSDictionary that contains the object as a value.

To receive the object passed along with the notification: create a method that will take the notification received from a receiving observer method and will check that the notification is the one you want. Then use a property on the notification that corresponds to the userInfo to get the NSDictionary. Lastly, extract the value from the dictionary.

Disabling the “listener”

If you run across a case where you need to make an object no longer listen for a notification there is another method. Where someObserver is the name of a particular observer instance.

For more information on NSNotificationCenter, swift syntax and working examples see the links below.

Thank you for reading!

Additional Resources:

Working example of NSNotification in Swift:

--

--