关于重复注册通知的问题

本文探讨了在iOS应用中,如果多次发送或注册相同的通知,会导致接收方多次响应,产生潜在的bug。通过示例代码展示了通知发送与接收的场景,并指出为防止错误,应当在注册通知前先注销相同的通知。

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

iOS中通过通知中心可以实现发送与接收通知的效果,其中若多次发送同一通知,对方就会多次响应,但如果多次注册通知,也会有多次响应的效果,这里容易比较隐形的bug。

多次发送:

//发送通知方
    //self 发送通知
    [[
NSNotificationCenter defaultCenter ] postNotificationName : @"justTest" object : nil ];
    [[
NSNotificationCenter defaultCenter ] postNotificationName : @"justTest" object : nil ];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"justTest" object:nil];

//接收通知方
- ( void ) resignNotification{
    [[
NSNotificationCenter defaultCenter ] addObserverForName : @"justTest" object : nil queue : nil
                                                 
usingBlock :^( NSNotification *note) {
                                                     
NSLog ( @"luozhiwei" );
                                                  }];
}
结果:
2015-07-25 16:15:46.491 multipleRegistrationNotification[5233:171998] luozhiwei
2015-07-25 16:15:46.491 multipleRegistrationNotification[5233:171998] luozhiwei
2015-07-25 16:15:46.491 multipleRegistrationNotification[5233:171998] luozhiwei

多次接收:

//发送通知方
[[ NSNotificationCenter defaultCenter ] postNotificationName : @"justTest" object : nil ];

//接收通知方
- ( void ) resignNotification{
    [[
NSNotificationCenter defaultCenter ] addObserverForName : @"justTest" object : nil queue : nil
                                                 
usingBlock :^( NSNotification *note) {
                                                     
NSLog ( @"luozhiwei" );
                                                  }];

    [[ NSNotificationCenter defaultCenter ] addObserverForName : @"justTest" object : nil queue : nil
                                                 
usingBlock :^( NSNotification *note) {
                                                     
NSLog ( @"luozhiwei" );
                                                  }];


    [[ NSNotificationCenter defaultCenter ] addObserverForName : @"justTest" object : nil queue : nil
                                                 
usingBlock :^( NSNotification *note) {
                                                     
NSLog ( @"luozhiwei" );
                                                  }];
}


结果:
2015-07-25 16:15:46.491 multipleRegistrationNotification[5233:171998] luozhiwei
2015-07-25 16:15:46.491 multipleRegistrationNotification[5233:171998] luozhiwei
2015-07-25 16:15:46.491 multipleRegistrationNotification[5233:171998] luozhiwei



结论:为了避免因此重复注册而造成错误,建议每次注册一个通知之前,可以先注销一次该通知。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值