NSNotification监听广播

本文介绍了一种基于广播机制的消息传递方法。通过 NotificationCenter 进行消息的发布与订阅,实现组件间的数据传递。文章详细展示了如何设置通知中心、注册监听者及发送与接收广播的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

     在处理监听传值的过程中,有一种广播机制,它通过注册广播中心,然后向各个收听者发送消息来实现传值。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];//移除当前所有通知

 

转载于:https://www.cnblogs.com/moxuexiaotong/p/4967053.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值