现在的位置: 首页 > 综合 > 正文

NSNotificationCenter消息通信机制介绍(KVO)

2017年12月07日 ⁄ 综合 ⁄ 共 1605字 ⁄ 字号 评论关闭

    NSNotificationCenter消息通信机制介绍(KVO)
作用:NSNotificationCenter是专门供程序在不同类间的消息通信而设置的
注册通知:
[[NSNotificationCenter defaultCenter] addObserver:(id)notificationObserver selector:(SEL)notificationSelector name:(NSString *)notificationName object:(id)notificationSender]
参数介绍:notificationObserver:观察者,即注册那个对象进行观察,不能为空
          notificationSelector:观察者对象收到通知以后调用的处理函数,只有一个NSNotification的参数
          notificationName:通知的名称,也就是通知的唯一标示,编译器通过这个找到通知
          notificationSender:观察者想要收到那个对象发来的通知,如果为空,则通知中心不在以及
//通知处理函数
-(void)handleNotification:(NSNotification *)nonatification{
    id obj =[notification object];//获取通知传递的对象
    NSDictionary *dic =[notification userInfo];//
}
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleNotification:) name:@"test" object:nil];

说明:如果notificationName为nil,那么Notification 将不在使用notificationName进行过滤,判断观察者是否接受通知,
      如果notificationSender为nil,那么Notification 将不在理解Object来进行过滤,决定观察者是否就收通知

发送通知:调用观察者处的方法
[NSNotificationCenter defaultCenter] postNotificationName:(NSString *)notificationName object:(id)notificationSender userInfo:(NSDictionary *)userInfo];
参数:
notificationName:通知的唯一标示,在注册的时候使用的名字
notificationSender:发出通知的对象
userInfo:关于通知的参数,可以为空

移除观察者:当观察者对象被销毁之前,要将观察者移除
[NSNotificationCenter defaultCenter] removeObserver:(id)notificationObserver name:(NSString *)notificationName object:(id)notificationSender];
参数:
notificationObserver: 观察者对象,不能为空,即那个对象进行观察
notificationName:注册的时候观察者的名称
notificaitonSender:要监听的的对象,即要监听那个对象

参考:https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSNotificationCenter_Class/Reference/Reference.html

示例代码:http://download.csdn.net/detail/u011872945/7894703

抱歉!评论已关闭.