NSNotification监听广播
2015-11-15 18:50
309 查看
在处理监听传值的过程中,有一种广播机制,它通过注册广播中心,然后向各个收听者发送消息来实现传值。Notification Center是一个单例对象。
实现方式如下:
1.设置通知中心:
2.设置收听者
实现:
3.移除通知
实现方式如下:
1.设置通知中心:
static MyNotificationCenter *center; @implementation MyNotificationCenter //用单例模式初始化 +(MyNotificationCenter *)sharedBoardCast { if (center == nil) { center = [[MyNotificationCenter alloc]init]; } return center; } -(void)sendMessage { NSDictionary *dict = @{@"name":@"moxue"}; //设置当前的通知中心并发送广播 [[NSNotificationCenter defaultCenter]postNotificationName:@"moxue" object:self userInfo:dict]; } @end
2.设置收听者
-(void)getCast { [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(cast:) name:@"moxue" object:nil];//注册听众 } -(void)cast:(NSNotification *)notice { NSLog(@"%@",notice.userInfo);//得到消息后处理事务 }
实现:
MyNotificationCenter *center = [MyNotificationCenter sharedBoardCast]; [center sendMessage]; Listener *ls = [[Listener alloc]init]; [ls getCast];
3.移除通知
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"moxue" object:self];//移除单个通知 [[NSNotificationCenterdefaultCenter] removeObserver:self];//移除当前所有通知
相关文章推荐
- Junit4中的新断言assertThat的使用方法
- Day3 编写ORM
- GEOS库的学习之二:简单几何图形的创建
- 隐藏listview的滚动条属性
- 机器学习基石第六讲 Theory of Generalization
- linux grep命令详解
- 转载安卓中的touch处理
- iOS app 的性能关注点
- ubuntu pyhton环境下安装和配置mysql及MySQL-python
- hadoop入门(1)——hadoop概述
- HihoCoder #1257 (2015-2016 ACM 北京站) Snake Carpet [构造题]
- 能ping通Linux 但是ssh连不上问题解决方法
- 父类引用指向子类对象(转)
- 活动图中的action与activity
- swift:无限图片轮播器
- 【Android】Scheme详解
- 【Java基础】用LinkedList实现一个简单栈的功能
- 文本挖掘分词mapreduce化
- O(1)空间子数组换位算法
- bsh for android : Socket Test