NSNotificationCenter 消息没有被触发 没收到消息 函数没执行

在使用NSNotificationCenter发送自定义消息时遇到监听器方法未执行的问题,已排除常见错误:正确设置消息名、确保先添加监听器后发送、发送时监听器未移除且对象存在。错误在于误解了addObserver方法中object参数含义,将其设为nil解决了问题。

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

用 NSNotificationCenter 发送自定义消息,结果监听者的方法没有被执行,看了半天也没发现错误,下面几点常犯的错误也不存在:

1,消息名用宏定义统一,消息名要在编译期就能确定,

2,一定要保证先addObserver,再post,

3,一定要确保post时还没有移除监听,

4,一定要保证post时监听对象还存在

各位如果有同样的问题先对照上面的提示自查 :)


下面贴上错误的代码:

//定义消息名
#define LoginSucceed @"LoginSucceed"
//在ViewController中添加监听
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onLoginSucceed:) name:LoginSucceed object:[UserInfoMgr instance]];

//在UserInfoMgr中post消息
NSNotification *noti = [NSNotification notificationWithName:LoginSucceed object:nil userInfo:[NSDictionary dictionaryWithObjectsAndKeys:@"succeed", @"login", nil]];
[[NSNotificationCenter defaultCenter] postNotification:noti];

发现onLoginSucceed:怎么都执行不到,才发现是addObserver方法的最后一个参数object我理解错了,以为要设置为发送消息的对象。将该参数设置为nil问题解决!!


说明:

    [[NSNotificationCenterdefaultCenter] addObserver:self
                                             selector:@selector(notePushRediectController:)
                                                 name:nPushRediectController
                                               object:nil];//这个object对应下面方法中的anObject,如果设置了需要对应起来才能触发。
//    - (void)postNotificationName:(NSString *)aName object:(id)anObject userInfo:(NSDictionary *)aUserInfo;
- (void)postNotificationName:(NSString *)aName object:(id)anObject   //anObject表示发送者。注册的地方可以设定指定的发送者,
														//只有当notification来自指定的发送者的时候才会触发。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值