码迷,mamicode.com
首页 > 其他好文 > 详细

通过NSNotificationCenter 发送通知

时间:2014-10-09 01:25:17      阅读:248      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   os   使用   ar   for   strong   

问题:

  想在APP中发布一条通知,同时允许其他对象接收通知并根据你广播的内容采取相应的行动.

讨论:

  通知中心是通知对象的派送中心, 例如,在用户使用 App 时如果键盘显示出来了,iOS 会发送一条通知到你的应用,程序中的任何对象都可以通过将自己添加到通知中心,作为一个观察者,来监听此通知。当对象的的生命周期即将结束时,需要将该对象从通知中心的派送表中移除。

  这样,一条通知就相当于一个消息被通知中心广播给它的观察者。通知中心是 NSNotificationCenter 类的一个实例对象。我们通过 NSNotificationCenter 的 defaultCenter 类的实例方法获取系统默认的通知中心实例; 

  通知本身就是 NSNotification 类的对象。一条通知对象有一个名称(标记为 NSString),它可以携带 2 条重要信息:(注意:你可以不需要使用 API 就给自己的通知命名,只要确保此条通知命名足够特别到不会与系统信息冲突.)

发送者:

  发送者就是消息的发起对象.观察者可以通过NSNotification类的object方法获得发送者.

用户信息字典:
  这是一个可选项字典。这个字典通常包含关于此条通知的更多信息。
   例如,当键盘在程序中显示出来时,iOS 会发送一个 UIKeyboardWillShowNotification 通知到通知中心,这个通知的用户信息字典会包含键盘的尺寸,以及键盘动画的时间。使用这些数据,观察者可以作一些决定,例如,让被键盘遮挡的界面重新正确的显示出来。 
 
方法:
  使用 NSNotificationCenter 中 default notificationcenter 的 postNotificationName:object:userInfo:的实例方法发布一条通知,其中携带一个对象(通常此对象激活通知)和一条关于用户信息的词典,词典中包含了关于此条通知和/或者激活通知的对象的额外信息。 
 
   为了建立 NSNotification 类的通知,要使用 NSNotification 的实例方法 notificationWithName:object:userInfo: class。

   注意:最好在通知名称前以 Notification 作为后缀。例如,允许通知名称为这样 ResultOfAppendingTwoStrings。然而,这样命名 ResultOfAppendingTwoStringsNotification 会更好。 

例子:
NSString *firstName = @"Anthony";
    NSString *lastName = @"Robbins";
    NSString *fullName = [firstName stringByAppendingString:lastName];
    NSArray *objects = [[NSArray alloc] initWithObjects:
                                                firstName,
                                                lastName,
                                                fullName,
                                                nil];
    NSArray *keys = [[NSArray alloc]initWithObjects:
                                                @"firstString",
                                                @"secondString",
                                                @"resultString",nil];
    NSDictionary *userInfo = [[NSDictionary alloc]initWithObjects:objects forKeys:keys];
    //创建一个通知实例
    NSNotification *notificationObject = [NSNotification notificationWithName:@"ResultOfAppendingTwoStringsNotification" object:self userInfo:userInfo];
    //创建一个通知中心来发送通知
    [[NSNotificationCenter defaultCenter]postNotification:notificationObject];

注意:有时我们没有必要为每个通知都制定发送者和用户信息字典参数.如果你不打算携带发送者和用户信息字典,建议使用 NSNotificationCenter 中postNotificationName:object:的实例方法,第一个参数传入一个字符串代表通知的名字,第二个参数传入 nil。

 

通过NSNotificationCenter 发送通知

标签:style   blog   color   io   os   使用   ar   for   strong   

原文地址:http://www.cnblogs.com/safiri/p/4011612.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!