iOS通知中心 NSNotificationCenter详解

本文详细介绍了NSNotification的使用方法,包括注册观察者、发送通知、监听通知并处理等关键步骤。同时强调了通知只会发送给已注册的监听者。

NSNotificationCenter的适用场景,原理机制,使用步骤等。

 

通知中心的使用顺序:先确保注册了观察者,因为发送通知是一瞬间的事,如果没有注册观察者,发送通知后再注册是不会收到的。

总结:通知只会发送给当前监听着的对象。

代码

//注册通知  在关心该通知的页面注册监听

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

 

//发送通知  一定要确保有注册了监听该通知才行

NSDictionary *dict =@{@"key":@"Value"};

    //创建通知

    NSNotification *notification =[NSNotification notificationWithName:@"tongzhi" object:nil userInfo:dict];

    //通过通知中心发送通知

    [[NSNotificationCenter defaultCenter] postNotification:notification];

//收到通知后回调的方法

- (void)tongzhi:(NSNotification *)text{

    NSLog(@"%@",text.userInfo[@"key"]);

    NSLog(@"-----接收到通知------");  

}

//在不需要接收通知的时候一定要移除监听

  [[NSNotificationCenter defaultCenter] removeObserver:self];

 

http://www.wtoutiao.com/a/1385824.html  这一篇总结得很不错

待总结...

转载于:https://www.cnblogs.com/GetLastError/p/4810990.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值