一,概述
KVO,即:Key-Value Observing,它提供一種機(jī)制年枕,當(dāng)指定的對(duì)象的屬性被修改后,則對(duì)象就會(huì)接受到通知乎完。簡單的說就是每次指定的被觀察的對(duì)象的屬性被修改后熏兄,KVO就會(huì)自動(dòng)通知相應(yīng)的觀察者了。
二、使用方法
系統(tǒng)框架已經(jīng)支持KVO摩桶,所以程序員在使用的時(shí)候非常簡單桥状。
1. 注冊(cè),指定被觀察者的屬性硝清,
2. 實(shí)現(xiàn)回調(diào)方法
3. 移除觀察
三辅斟、代碼示例
假設(shè)一個(gè)場景,定義一個(gè)Person類芦拿,屬性有name,age,當(dāng)年齡改變時(shí)士飒,顯示當(dāng)前年齡
1.定義Person類
@interfacePerson :NSObject
@property(strong,nonatomic)NSString*name;
@property(nonatomic,assign)NSIntegerage;
@end
2.在controller中引入Person,實(shí)例化并監(jiān)聽屬性
當(dāng)單擊時(shí)蔗崎,改變age,實(shí)現(xiàn)回調(diào)方法
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void*)context
@interfaceViewController()
{
Person*personKVO;
}
@end
@implementationViewController
- (void)viewDidLoad {
[superviewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
personKVO= [[Personalloc]init];
[personKVOsetValue:@"admin"forKey:@"name"];
[personKVOsetValue:@"20"forKey:@"age"];
[personKVOaddObserver:selfforKeyPath:@"age"options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOldcontext:nil];
}
- (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event
{
//[personKVO setValue:@"21" forKey:@"age"];
[personKVOsetAge:13];
}
- (void)observeValueForKeyPath:(NSString*)keyPath ofObject:(id)object change:(NSDictionary*)change context:(void*)context
{
if([keyPathisEqual:@"age"])
{
idage =[personKVOvalueForKey:@"age"];
NSLog(@"age改變%@",age);
}
}
- (void)didReceiveMemoryWarning {
[superdidReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
當(dāng)Model值發(fā)生改變時(shí)酵幕,監(jiān)聽對(duì)象會(huì)立即得到通知,適用于界面數(shù)據(jù)展示缓苛。
簡單隨筆裙盾,愿與君共勉。