iOS开发8-NSNotificationCenter的使用

iOS开发8-NSNotificationCenter的使用




  代码下载(Xcode7.0.1)
 有问题请联系博主,邮箱:nathanlee1987@aliyun.com

        iOS 提供了一种 "同步的" 消息通知机制,观察者只要向消息中心注册, 即可接受其他对象发送来的消息,消息发送者和消息接受者两者可以互相一无所知,完全解耦。
这种消息通知机制可以应用于任意时间和任何对象,观察者可以有多个,所以消息具有广播的性质,只是需要注意的是,观察者向消息中心注册以后,在不需要接受消息时需要向消息中心注销,这种消息广播机制是典型的“Observer”模式。

1、观察者注册
第一个参数addObserver:观察者对象
第二个参数selector:        得到通知后的处理方法
第三个参数name:           通知的名称
第四个参数object:           通知传递过来的参数对象
 //注册
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(doSomething:) name:@"HZ123" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(doSomething2:) name:@"HZ124" object:nil];

2、被观察者发送消息通知
- (IBAction)nextbutton:(id)sender {
      //发出广播---尽量少用-消耗资源
      //给整个程序发送通知
    [[NSNotificationCenter defaultCenter] postNotificationName:@"HZ123" object:@"HZ123"];
     [[NSNotificationCenter defaultCenter] postNotificationName:@"HZ124" object:@"HZ124"];
}

3、观察者处理得到的通知

-(void)doSomething:(id)sender{
    NSLog(@"ViewController收到:%@",sender);
    //[[NSNotificationCenter defaultCenter]removeObserver:self name:@"HZ123" object:nil];
    [[NSNotificationCenter defaultCenter]removeObserver:self ];
    NSLog(@"ViewController已经移除HZ123观察");
}

-(void)doSomething2:(id)sender{
    NSLog(@"ViewController收到:%@",sender);
  
    //[[NSNotificationCenter defaultCenter]removeObserver:self ];
 
}
4、移除观察者
[[NSNotificationCenter defaultCenter]removeObserver:self name:@"HZ123" object:nil];//单个移除
    [[NSNotificationCenter defaultCenter]removeObserver:self ];//移除所有



   代码下载(Xcode7.0.1)
 有问题请联系博主,邮箱:nathanlee1987@aliyun.com

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值