1.29. Sending Notifications with NSNotificationCenter
Problem
You want to broadcast an event in your app and allow any object that is willing to listen to it to take action, depending on the notification that you are broadcasting.
Solution
Use the postNotificationName:object:userInfo: method
of the default notification center of type NSNotificationCenter to post a notification
that carries an object (usually the object that fires the notification)
and a user-info dictionary that can carry extra information about the
notification and/or the object that fires the notification.
Discussion
Notification centers are dispatch centrals for notification objects.
For instance, when the keyboard pops up anywhere while
the user is inside your app, iOS will send a notification to your app.
Any object inside your app willing to listen to this notification can
add itself to the default notification center as an
observer for that particular notification. Once
your object’s lifetime comes to an end, it must remove itself from the
notification center’s dispatch table. As a result, a notification is a
message that gets broadcasted to observers through a notification
center. A notification center is an instance of NSNotificationCenter class. We retrieve the
default notification center object using the defaultCenter class method of NSNotificationCenter.
Notifications are objects of type NSNotification. A notification object has a
name (specified as NSString) and can
carry two key pieces of information:
Note ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access