通知 NSNotification:
通过学习KVO,我们发现KVO是一种简单的观察者设计模式,设计到两个对象,分别是观察者和被观察者.
这种方式本质有很大的局限性,那么OC的 ‘Foundation’ 框架又为开发者提供了新的一种观察者设计模式,即通知
通知,是一种发送给一个或多个观察者,用来通知其在程序中发生了某个时间的消息。
Cocoa中的通知机制遵循的是一种广播的模式,他是一种 程序中时间的 发起者 或者是 处理者 和 其他想要知道该时间的对象 沟通的一种方式。
消息的接受者,也就是观察者响应该时间来改变自己的UI,行为或状态
//初始化一个通知(NSNotification)的实例对象
NSNotification *notification1 = [NSNotification notificationWithName:@"通知名称1" object:self];
NSNotification *notification2 = [NSNotification notificationWithName:@"通知名称2" object:self userInfo:@{@"content":@"hello world"}];
//userInfo 表示通知的内容
//创建一个通知中心 单例类,拿到通知中心的单例
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
创建一个通知的发送机制的方法如下:
1.注册监听者,并实现在需要的时候回调方法
2.在需要的时候,被监听者的对象去到通知中心发送消息
3.移除监听者
//重写init方法
- (id)init{
if (self = [super init]) {
//注册监听者
/*
1.addObserver 表示要去接受通知的对象
2.selector 接收通知要回调的相应方法
3.name 接收通知的名字
4.object 表示发起通知的对象,一般为nil
*/
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationAction:)name:@"通知名称2"
object:nil];
}
return self;
}
//监听到通知后回调的方法
- (void)notificationAction:(NSNotification *)notification{
NSLog(@"%@",notification.userInfo);
}
//移除监听者
- (void)dealloc{
//移除某个通知的监听者
[[NSNotificationCenter defaultCenter]removeObserver:self
name:@"通知名称2"object:nil];
// [[NSNotificationCenter defaultCenter]removeObserver:self];
//表示移除所有通知的监听者
}
//在ViewControllor.m文件中实现
Student *student = [[Student alloc]init];
[center postNotification:notification2];
//下面两种方法,我们不需要创建一个notification,直接在里面书写内容即可
//[center postNotificationName:@"通知名称3" object:self];
//[center postNotificationName:@"通知名称4" object:self userInfo:@{@"":@""}];
通知与KVO的区别
KVO只能监听属性的变化,通过NSString类型的属性名来实现。实现了自动坚挺,当属性值变化时,会自动通知观察者,不用再添加代码。但是观察者得持有被观察的引用,以便被观察者注册观察者,耦合性太高,不利于代码的维护。
NSNotification比较灵活,可以监听的内容不局限于属性的变化,还可以对多种多样的状态变化进行监听,监听范围广,使用也更灵活。但是需要被观察者手动发送通知,观察者注册监听后才能响应,比KVO多了发送通知的一步。但是观察者注册监听不需要被观察者的引用,没有耦合性,利于代码的维护