kvo既是Key-Value Observing,它提供一种机制,就是说指定的对象的属性被修改后,那么这个对象就会受到通知。也就是说,当制定的被观察者的属性被修改后,kvo会通知相应的观察者。
kvo的一般步骤就是
1,注册,制定被观察者的属性
2,实现回调方法
3,注销观察
kvo的实例
孩子与护士的实例
在child的头文件里添加一个属性
@interface child : NSObject
@property(nonatomic,assign)NSInteger age;
@end
在child.m里面实现初始化,并加上定时器
@implementation child
-(id)init
{
self =[super init];
if (self) {
self.age = 10;
[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerAction:) userInfo:nil repeats:YES];
}
return self;
}
-(void)timerAction:(NSTimer *)timer
{
//self.age--;
_age--;
[self setValue:[NSNumber numberWithInteger:_age] forKey:@"age"];
}
@end
在nurse.h里面添加一个child属性和声明一个初始化方法
@class child;
@interface nurse : NSObject
@property(nonatomic,strong)child *child;
-(id)initWithChild:(child *)child;
@end
在nurse.m里面实现初始化方法并注册观察者,实现回调方法,销毁观察者
@implementation nurse
-(id)initWithChild:(child *)child
{
self =[super init];
if (self) {
self.child =child;
[ self.child addObserver:self forKeyPath:@"age" options:NSKeyValueObservingOptionOld|NSKeyValueObservingOptionNew context:nil ];
}
return self;
}
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
NSLog(@"%@",change);
}
<pre name="code" class="objc">-(void)dealloc
{
[_child removeObserver:self forKeyPath:@"age"];
[super dealloc];
}
@end
在main.m里初始化child和nurse
#import "child.h"
#import "nurse.h"
int main(int argc, const char * argv[])
{
@autoreleasepool {
child *children =[[ child alloc]init];
nurse *ne =[[nurse alloc]initWithChild:children];
[[NSRunLoop currentRunLoop]run];
}
return 0;
}
这样就可以实现了kvo