今天整理了一下NSNotificationCenter的内容,发出来与小伙伴们一起分享下。
首先你要了解,iOS 提供的这种 "同步的" 消息通知机制,观察者只要向消息中心注册, 即可接受其他对象发送来的消息,消息发送者和消息接受者两者可以互相一无所知,完全解耦。
这种消息通知机制可以应用于任意时间和任何对象,观察者可以有多个,所以消息具有广播的性质,只是需要注意的是,观察者向消息中心注册以后,在不需要接受消息时需要向消息中心注销,这种消息广播机制是典型的“Observer”模式。
2016-09-9 补图
其次,NSNotification在类与类之间传递消息参数时,具体使用方法有四个步骤:1、观察者注册通知 2、发送消息通知 3、观察者处理消息 4、移除消息观察者。
1、观察者注册通知
<span style="font-family:Microsoft YaHei;font-size:14px;"><span style="font-family:Microsoft YaHei;font-size:14px;">[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getUserProfileSuccess:) name:@"Notification_GetUserProfileSuccess" object:nil];</span></span>
notificationObserver 观察者 : selfnotificationSelector 处理消息的方法名: getUserProfileSuccess
notificationName 消息通知的名字: Notification_GetUserProfileSuccess
notificationSender 消息发送者 : 表示接收哪个发送者的通知,如果第四个参数为nil,接收所有发送者的通知
2、发送消息通知
<span style="font-family:Microsoft YaHei;font-size:14px;"><span style="font-family:Microsoft YaHei;font-size:14px;">[[NSNotificationCenter defaultCenter] postNotificationName:@"Notification_GetUserProfileSuccess" object:@{@"key":@"V"} userInfo:nil];</span></span>
notificationName 消息通知的名字: Notification_GetUserProfileSuccess
notificationSender 消息发送者: userProfile
3、观察者处理消息
<span style="font-family:Microsoft YaHei;font-size:14px;">- (void) getUserProfileSuccess: (NSNotification*) aNotification
{
NSDictionary *dic = [aNotification object];
}</span>
NSNotification 是object,不管你传的是字符串、数组、还是字典,只要保证之前发送时的与我们接收时的是相同类型就好。
4、移除消息观察者
虽然在 IOS 用上 ARC 后,不显示移除 NSNotification Observer 也不会出错,但是这是一个很不好的习惯,不利于性能和内存。
注销观察者有2个方法:
a. 最优的方法,在 UIViewController.m 中:
<span style="font-family:Microsoft YaHei;font-size:14px;"><span style="font-family:Microsoft YaHei;font-size:14px;">-(void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver: self];
}</span></span>
b. 单个移除:
<span style="font-family:Microsoft YaHei;font-size:14px;"><span style="font-family:Microsoft YaHei;font-size:14px;">[[NSNotificationCenter defaultCenter] removeObserver:self name:@"Notification_GetUserProfileSuccess" object:nil];
</span></span>
感谢观看,学以致用更感谢~