概述
KVO,即:Key-Value Observing,它提供一種機制,當指定的對象的屬性被修改后,則對象就會接受到通知。簡單的說就是每次指定的被觀察的對象的屬性被修改后,KVO就會自動通知相應的觀察者了。
KVO其實也是“觀察者”設計模式的一種應用。我的看法是,這種模式有利于兩個類間的解耦合,尤其是對于 業(yè)務邏輯與視圖控制 這兩個功能的解耦合。
模型
.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屬性發(fā)生變化,就會調(diào)用此函數(shù)*/
- (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:@"%@現(xiàn)在的年齡是: %ld", self.person.name, self.person.age];
}
}