Simon Shi

放飞梦想,专注于Mobile开发

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: :: 订阅 订阅 :: 管理 ::

From: http://www.idev101.com/code/Cocoa/Notifications.html

Notifications are an incredibly useful way to send messages (and data) between objects that otherwise don't know about each other. Think of it like a radio station broadcasting messages: the station (sender) broadcasts the message, and listeners can choose to listen in and receive some (or all) of the broadcast messages.

For example, you might have a network reachability check in your app delegate, and post notifications whenever the reachability changes. Other objects would listen for that notification and react accordingly when the network goes up or down.

Some Cocoa frameworks send notifications when certain events happen. In iOS 4.0 and up, the application sends notifications when an app is about to move the background... and when it returns from the background. Your app's objects and controllers can listen for these notifications and stop actions (or save data) when the app is about to quit, and resume when it becomes active again.

Posting Notifications

To post a notification, the sending object calls the following method:

[[NSNotificationCenter defaultCenter] postNotificationName:@"reachabilityChanged" object:self];

The notification name can be any NSString. object should be self (the sender), or nil.

If you need to pass data along with the notification, use the following method and pass an NSDictionary as the userInfo argument:

BOOL isReachable = YES;
NSDictionary *dataDict = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:isReachable] 
                                                     forKey:@"isReachable"];

[[NSNotificationCenter defaultCenter] postNotificationName:@"reachabilityChanged" object:self userInfo:dataDict];

Listening for Notifications

To listen for notifications, an object must:

1. Add itself as on observer. This can go in the object's init method, or the controller's viewDidLoad*.

[[NSNotificationCenter defaultCenter] addObserver:self 
                                         selector:@selector(handleReachabilityChange:)        
                                             name:@"reachabilityChanged" 
                                           object:nil];

The object: argument can either be a specific object to listen for notifications from, or nil to listen for notifications from any object.

2. Declare and implement the method named in the @selector:

- (void)handleReachabilityChange:(NSNotification *)note {
    NSDictionary *theData = [note userInfo];
    if (theData != nil) {
        NSNumber *n = [theData objectForKey:@"isReachable"];
        BOOL isReachable = [n boolValue];
        NSLog(@"reachable: %d", isReachable);
    }
}

The NSNotification object has three key properties you can access: the notification name, the sending object, and the userInfo dictionary that was passed.

3. Remove itself as an observer before the object is deallocated:

-(void) dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [super dealloc];
}

Don't forget this part! If you fail to remove the object as an observer, then the notification center will send notifications to your deallocated object, which will crash your app.

*If your view controller only needs to respond to notifications while the view is visible, you may want to put the addObserver code in viewDidAppear, and removeObserver in viewDidDisappear. This way your controller won't be responding to notifications when it isn't the current view. (This is particularly important if you're using a navigation controller or tab bar controller, where the controller object may exist but its view isn't the current view - or worse, its view has been unloaded.)

Additional References

You can also access the documentation in Xcode by typing ⌘/ to launch the documentation window.

 

posted on 2012-10-08 16:41  Simon Shi  阅读(216)  评论(0编辑  收藏  举报