Notifications

Notifications are messages that are sent between objects. Unlike delegates, which are specifically linked to the object sending the message, notifications are broadcast and intercepted without any link between the sender and receiver. In fact, there can even be multiple receivers listening for a notification. Think of it like a radio station, which broadcasts a program whether it has listeners or not, and like radio receivers which can tune in to receive that program.

The NSNotification object is used to build a message. A message contains three properties:

  • The name is the message identifier.
  • The object is the sender of the message.
  • The userInfo is an NSDictionary containing information about the message.

You can create an NSNotification using the notificationWithName:object:userInfo: class method. Chances are, however, that you’ll never create a notification directly, but do so through the notification center.

Notification Center

The NSNotificationCenter provides a mechanism for broadcasting information within a program. This would be the radio station in our analogy.

Each app has a default notification center you can use. You typically will never need to create your own. To access this notification center, you use the defaultCenter class method.

Listening for Notifications

Any object can register with a notification center to receive NSNotifications using the addObserver:selector:name:object: method. The object parameter is used to set a specific notification sender, but you can also pass nil to register for all notifications identified by the name parameter.

An object can also register for a notification using a block handler. This is done with the addObserverForName:object:queue:usingBlock: method. The queue parameter is used in multithreading environments, but since we haven’t looked at that yet, you can just pass nil to use the main thread.

You use removeObserver:name:object: to stop listening for a notification.

You can also call removeObserver: to stop listening for all notifications.

Posting Notifications

Posting notifications is also done through the NSNotificationCenter, using either the postNotificationName:object: or postNotificationName:object:userInfo: methods, depending on whether or not you need to pass info along.

Comments are closed.