概述
KVO,即:Key-Value Observing,它提供一种机制,当指定的对象的属性被修改后,则对象就会接受到通知。简单的说就是每次指定的被观察的对象的属性被修改后,KVO就会自动通知相应的观察者了。
KVO其实也是“观察者”设计模式的一种应用。我的看法是,这种模式有利于两个类间的解耦合,尤其是对于 业务逻辑与视图控制 这两个功能的解耦合。
模型
.h
#import <Foundation/Foundation.h>
@interface Person : NSObject
@property(nonatomic,copy)NSString *name;
@property(nonatomic,assign)NSInteger age;
@end
控制器
- (void)viewDidLoad {
[super viewDidLoad];
self.person = [[Person alloc]init];
self.person.name = @"王二";
self.person.age = 18;
[self.person addObserver:self forKeyPath:@"age" options:NSKeyValueObservingOptionNew context:nil];
//UILabel
self.ageLabel = [[UILabel alloc]init];
self.ageLabel.frame = CGRectMake(10, 200, 300, 30);
self.ageLabel.text = [NSString stringWithFormat:@"%@ 的年龄是: %ld 岁",self.person.name,self.person.age];
[self.view addSubview:self.ageLabel];
//按钮
UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(50, 300, 200, 30)];
[btn setTitle:@"王二增加五岁" forState:UIControlStateNormal];
btn.backgroundColor = [UIColor redColor];
[btn addTarget:self action:@selector(clickBtn) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn];
}
-(void)clickBtn{
self.person.age += 5;
}
/* KVO function, 只要object的keyPath属性发生变化,就会调用此函数*/
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if ([keyPath isEqualToString:@"age"] && object == self.person) {
self.ageLabel.text = [NSString stringWithFormat:@"%@现在的年龄是: %ld", self.person.name, self.person.age];
}
}
网友评论