在昨天的时候复习了KVO:http://www.jianshu.com/p/58198934f01a ,今天我们来看一下另外一个类似的功能技术:通知(Notification).
跟KVO的一些区别
Notification和KVO功能很像,也是用于监听操作的,并且两个都能一对多.但是和KVO不同的是,KVO只用来监听属性值的变化,这个发送监听的操作是系统控的,我们控制不了,我们只能控制监听操作,类似于Android中系统发送的广播,我们只能接受。但是通知就不一样了,他的监听发送也是又我们自己控制,我们可以在任何地方任何时机发送一个通知,类似于Android中开发者自己发送的广播。从这一点看来,通知的使用场景更为广泛了。
代码
还是昨天写的那个例子,child和nanny两个类,其中child有一个cleanValue(干净指数),通过设置cleanValue的值满足什么条件时发送一个通知,然后nanny接收到这个消息之后给child洗澡,使得child的cleanvalue的值重新恢复到初始值.
Child.m
#import <Foundation/Foundation.h>
@interface Child : NSObject
@property (nonatomic, assign) NSInteger cleanValue;
@end
创建一个Child类,其中包含了_cleanValue属性.
child.m
#import "Child.h"
@implementation Child
- (instancetype)init
{
self = [super init];
if (self) {
_cleanValue = 100;
[NSTimer scheduledTimerWithTimeInterval:1
target:self
selector:@selector(timeAC:)
userInfo:nil
repeats:YES];
}
return self;
}
- (void)timeAC:(NSTimer *)timer {
self.cleanValue --;
_cleanValue = _cleanValue - 3;
NSLog(@"cleanValue:%ld", _cleanValue);
/*
postNotificationName:通知名字
object:发通知的对象
*/
if (_cleanValue < 90) {
// 发出一个通知
NSLog(@"发出需要洗澡的通知");
[[NSNotificationCenter defaultCenter] postNotificationName:@"cleanValueNotification" object:self];
}
}
@end
定义了一个定时器,但是我们看到这里的timerAction方法中:当cleanvalue的值小于90时就发送一个通知:NSNotificationCenter
其中第一个参数是通知的名字,这个名字跟后面接受通知的名字必须要一致.
第二个参数是可以传送过去的对象,这里是child *
Nanny.h
#import <Foundation/Foundation.h>
@interface Nanny : NSObject
@end
没什么好讲的
Nanny.m
#import "Nanny.h"
#import "Child.h"
@implementation Nanny
- (instancetype)init{
self = [super init];
if (self) {
// 注册一个通知接收器,监听名字为"cleanValueAction"的通知
// addObserver:在这里就是保姆为接收者
// selector:接到通知后调用的方法
// name:指定接收通知的名字
// object:指定接收某个对象的通知
// _child = child;
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(cleanValueAction:) name:@"cleanValueNotification" object:nil];
}
return self;
}
- (void)cleanValueAction:(NSNotification *)notification {
NSLog(@"收到给小孩洗澡的通知");
Child *child = (Child *)notification.object;
child.cleanValue = 100;
}
- (void)dealloc {
// 指定名字移除接收器
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"cleanValueAction" object:nil];
}
@end
addObserver:在这里就是保姆为接收者
selector:接到通知后调用的方法
name:指定接收通知的名字
object:指定接收某个对象的通知
处理通知的方法
void)cleanValueAction:(NSNotification *)notification {
NSLog(@"收到给小孩洗澡的通知");
Child *child = (Child *)notification.object;
child.cleanValue = 100;
}
这里会传递一个NSNotification对象,通过object属性可以获取到监听对象了,因为我们在发送通知的时候传递过来的这个对象。那么这里我们就可以获取监听对象的属性值了,但是这里我们如果想知道属性值变化前和变化后的值,我们可以在Children类中在定义一个属性专门用来记录旧的属性值,这样就可以了。
注意
要在最后设置dealloc方法,将所有的观察者移除,防止内存泄漏
- (void)dealloc {
// 指定名字移除接收器
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"cleanValueAction" object:nil];
}
removeobserve可以移除所有的观察者,因为有时候可能不止一个.