iOS开发 通知中心传值以及仅通知

本文详细介绍了如何在iOS应用中使用通知中心来实现不同控制器之间的通信。包括无参数触发动作和带参数信息传递两种场景,并强调了正确移除观察者的重要性。

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

利用通知中心传递信息在一个控制器传给上一个控制器的情况经常用到

不传值时常用于触发某种action:

       在发送方:

[[NSNotificationCenter defaultCenter]postNotificationName:@"post" object:self];
       在接收方:

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

在传值时候

       发送方:

[[NSNotificationCenter defaultCenter]postNotificationName:@"post" object:self userInfo:@{@"start":_start.text,@"end":_end.text,@"time":_timeTextField.text}];

       接收方:

[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(action:) name:@"successQuery" object:nil];
 其中action有个“: ”就是传过来的字典,需要解析

-(void)action:(NSNotification*)notification{
    NSDictionary *nameDictionary = [notification userInfo];
    seachMsg = (NSMutableDictionary*)nameDictionary;
    ......
}

很重要一点

如果观察者如果对通知没兴趣,也即在接受通知消息的控制器消失时或者不用时,应该移除对通知的观察

-(void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
或者

[[NSNotificationCenter defaultCenter] removeObserver:self name:@"NAME"
                                              object:test];//object 与注册时相同




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值