您的位置:首页 > 其它

NSNotification监听广播

2015-11-15 18:50 309 查看
在处理监听传值的过程中,有一种广播机制,它通过注册广播中心,然后向各个收听者发送消息来实现传值。Notification Center是一个单例对象。



实现方式如下:

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];//移除当前所有通知
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: