iOS DeveloperiOS 开发成长中心iOS 你不知道的新鲜事

iOS开发--广播通知

2016-11-16  本文已影响1918人  爱吃鱼的小灰
// 在需要接收通知消息的.m文件中写入
 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(logOutSuccess:)  name:@"isLogOutSuccess" object:nil];

notificationObserver 观察者 : self

notificationSelector 处理消息的方法名: logOutSuccess:
notificationName 消息通知的名字: isLogOutSuccess

notificationSender 消息发送者 : 表示接收哪个发送者的通知,如果第四个参数为nil,接收所有发送者的通知
(2) 发送消息通知

// 在需要发送数据的.m文件中写入
[[NSNotificationCenter defaultCenter] postNotificationName:@"isLogOutSuccess" object:returnMsg];
// 这个比第一个多了个参数就是userInfo(参数类型是字典)
[[NSNotificationCenter defaultCenter] postNotificationName:@"isLogOutSuccess" object: returnMsg userInfo:[NSDictionary dictionaryWithObject:@"value" forKey:@"key"]];

notificationName 消息通知的名字: isLogOutSuccess
notificationSender 消息发送者: returnMsg
userInfo 消息传递的数据信息:可以写入nil
(3)观察者处理消息

// 在注册通知的控制器中写入该方法
  -(void) isLogOutSuccess:(NSNotification*)notification{
     NSString *nameString = [notification name];
     NSString *objectString = [notification object];
     NSDictionary *dictionary = [notification userInfo];为nil要有这行代码哦
   // 当你拿到这些数据的时候你可以去做一些操作
}

NSNotification 接受到的消息信息,主要含:

Name: 消息名称 isLogOutSuccess
object: 消息发送者 returnMsg

userInfo: 消息传递的数据信息

观察者注销,移除消息观察者

虽然在 IOS 用上 ARC 后,不显示移除 NSNotification Observer 也不会出错,但是这是一个很不好的习惯,不利于性能和内存。

 -(void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
 If you see the method you don't need to call [super dealloc]; here, only the method without super dealloc needed.

2、单个移除

[[NSNotificationCenter defaultCenter] removeObserver:self name:@"isLogOutSuccess" object:nil];
上一篇 下一篇

猜你喜欢

热点阅读