用 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来自指定的发送者的时候才会触发。