O'Reilly logo

iOS 7 Programming Cookbook by Vandad Nahavandipoor

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 *const kNotificationName = @"NotificationNameGoesHere";

@implementation AppDelegate

- (BOOL)            application:(UIApplication *)application
  didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
    
    NSNotification *notification = [NSNotification
                                    notificationWithName:kNotificationName
                                    object:self
                                    userInfo:@{@"Key 1" : @"Value 1",
                                               @"Key 2" : @2}];
    
    [[NSNotificationCenter defaultCenter] postNotification:notification];
    
    self.window = [[UIWindow alloc]
                   initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    return YES;
}

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required