IOS学习笔记之通知

1、通知的概念

    IOS系统提供了NSNotificationCenter(通知中心)设计,这种设计允许开发者以松耦合的方式实现IOS 应用内各个对象之间的通信。

    NSNotificationCneter实现了观察者模式,允许应用的不同对象之间以松耦合的方式进行通信。NSNotificationCenter就是IOS SDK为开发者实现的观察者模式,这种设计模式的示意图如图所示:


    NSNotificationCenter相当于一个"消息中心",首先由observer所在的对象向NSNotificationCenter进行注册,表明observer对哪些NSNotification感兴趣。在没有任何对象发送NSNotification的情况下,这些observer都处于静止状态,不会执行任何代码。只要有一个对象发送NSNotification之后,所有在NSNotificationCenter注册过的,且对该NSNotification的名称对应的observer都会被激发。

    IOS SDK 中很多对象都会发送NSNotification

    (1)当应用程序状态改变时,UIApplication会对外发送NSNotification

    (2)当键盘出现时,UIWindow会对外发送NSNotification

    (3)当UITableView选中行发生改变时,UITableView会对外发送NSNotification

      ...

    (4)查看UIKit的API文档,专门有一个分类列出该组件可能发出的NSNotification

2、通知常用的方法

    (1)获取单例模式

     [NSNotificationCenter defaultCenter];

    (2)注册监听者

    -addObserver:selector:name:object:该方法第一个参数为监听者,第二个参数selector参数用于指定监听者的监听方法,第三个参数name指定通知的名称,第四个参数object代表发送者对象(poster),如果object参数为nil,则代表用于监听任何对象发出的通知。

    (3)删除监听者

     -removeObserver:name:object:删除对指定监听者(通过name参数指定)、指定通知的监听。

    (4)发送通知

    -postNotificationName:object:该方法第一个参数指定通知的名称,第二个参数指定通知的object

3、通知的应用

     NSNotificationCenter只允许同一个程序中的不同对象之间进行通信,它们不能跨越不同的应用。

    我们可以使用NSNotificationCenter监听自定义通知,也可以使用NSNotificationCenter监听系统组件的通知。

//监听自定义消息

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

-(void)receiveMsg:(NSNotification *)notification{

    NSLog(@"收到通知名称为:%@",notification.name);

    NSLog(@"通知传递的对象为:%@",notification.object);   

}

[[NSNotificationCenter defaultCenter] postNotificationName:@"test" object:nil];



//监听系统消息

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardWillShow:) name:UIKeyboardWillShowNotification object:nil];

-(void)keyBoardWillShow:(NSNotification *)notification{

    NSLog(@"键盘将要弹出");

}


4、NSNotifiication的含义

    NSNotification代表Poster(请求者)与observer(监听者)之间的信息载体,该对象包含如下只读属性:

    (1)name:该属性代表通知的名称,在创建监听者时就是根据该名称进行注册的。

    (2)object:该属性代表该通知传递的对象。

    (3)userInfo:该属性是一个NSDictionary,用于携带通知的附加信息。











  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值