通知 NSNotification
通过学习KVO,我们发现KVO是一种简单的观察者设计模式,涉及到两个对象,分别是观察者和被观察者。这种方式实质是有很大的局限性,那么OC的‘Foundation’框架又为开发者提供了新的一种观察者设计模式,即通知。
通知,是一种发送给一个或多个观察者,用来通知其在程序中发送了某个事件的消息。Cocoa中的通讯机制遵循的是一种广播的模式。它是一种程序中事件的发起者或是处理者和其他想要知道该事件的对象沟通的一种方式。消息的接受者,也就是观察者响应该事件来改变自己的UI、行为或者状态。
在OC中,使用NSNotification类来表示一个通知。
//初始化一个通知(NSNotification)的实例对象
name:通知名称
object:通知发起人
//ViewController.m
NSNotification *notification1 = [NSNotification notificationWithName:@"通知名称2" object:self ];
userInfo:通知内容
NSNotification *notification2 = [NSNotification notificationWithName:@"通知名称1" object:self userInfo:@{@"content":@"hello world"}];
//通知中心 单例类,拿到通知中心的单例
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
/*
建立通知的发送机制,如下:
1.注册相关的监听者,并实现在需要的时候回调收到通知时的方法
2.在需要的时候,被监听者的对象去到通知中心发送消息
3.在‘dealloc’方法中,移除通知
*/
Student *student = [[Student alloc] init];
[center postNotification:notification2];
[center postNotificationName:@"通知3" object:self];
[center postNotificationName:@"通知名称2" object:self userInfo:@{@"content":@"aaaaaa"}];
Weather *weather = [[Weather alloc]init];
PhoneUser *phoneUser = [[PhoneUser alloc]init];
[weather sendMessage];
//Weather.m
-(void)sendMessage{
[[NSNotificationCenter defaultCenter]postNotificationName:@"WeatherAndPhoneUser" object:self userInfo:@{@"weather":@"Sunny"}];
}
//PhoneUser.m
-(id)init{
if (self = [super init]){
//注册成为监听者
[NSNotificationCenter defaultCenter]addObserver:self
selector:@selector(notificationAction:)
name:WeatherAndPhoneUser
object:nil];
}
return self;
}
//回调
-(void)notificationAction:(NSNotification *)notification{
NSDictionary *dic = notification.userInfo;
NSLog(@"%@",dic);
}
//移除监听者
-(void)dealloc{
[[NSNotificationCenter defaultCenter] removeObserver:self
}
//Student.m
-(id)init{
if (self = [super init]){
//注册监听者
/*
1.要去接收通知的对象
2.接受通知要回调的相应方法
3.接受通知的名字
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationAction:) name:@"通知名称2" object:nil];
}
return self;
}
//监听到通知后回调的方法
-(void)notificationAction:(NSNotification *)notification{
NSLog(@"%@",notification.userInfo);
}
//移除监听者
-(void)dealloc{
//移除某个通知的监听者
[[NSNotificationCenter defaultCenter]removerObserver:self name:@"通知名称2" object:nil];
}
//移除所有通知的监听者
[[NSNotificationCenter defaultCenter]removeObserver:self];
NSLog(@"dddd");
}