17.1. Sending Notifications
Problem
You want to decouple parts of your app and send a notification where it can be picked up by another component in your app.
Solution
Compose an instance of NSNotification and broadcast it to your app
using the class’s postNotification:
method. You can get an instance of the notification center using its
defaultCenter class method, like
so:
#import "AppDelegate.h"NSString*constkNotificationName=@"NotificationNameGoesHere";@implementationAppDelegate-(BOOL)application:(UIApplication*)applicationdidFinishLaunchingWithOptions:(NSDictionary*)launchOptions{NSNotification*notification=[NSNotificationnotificationWithName:kNotificationNameobject:selfuserInfo:@{@"Key 1":@"Value 1",@"Key 2":@2}];[[NSNotificationCenterdefaultCenter]postNotification:notification];self.window=[[UIWindowalloc]initWithFrame:[[UIScreenmainScreen]bounds]];self.window.backgroundColor=[UIColorwhiteColor];[self.windowmakeKeyAndVisible];returnYES;}
Discussion
A notification object is encapsulated in an instance of the
NSNotification class. A notification
object on its own is really nothing until it has been posted to the app
using a notification center. A notification object has three important
properties:
- Name
This is a string. When a listener starts listening for notifications, it has to specify the name of the notification, as we will see later in this chapter. If you are posting a notification in a class of yours, ensure that the name of that notification ...
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