一,概述
KVO,即:Key-Value Observing,它提供一种机制,当指定的对象的属性被修改后,则对象就会接受到通知。简单的说就是每次指定的被观察的对象的属性被修改后,KVO就会自动通知相应的观察者了。
二,使用方法
系统框架已经支持KVO,所以程序员在使用的时候非常简单。
1. 注册,指定被观察者的属性,
2. 实现回调方法
3. 移除观察
三,实例:
假设一个场景,股票的价格显示在当前屏幕上,当股票价格更改的时候,实时显示更新其价格。
//1.定义DataModel,
@interface StockData : NSObject {
NSString * stockName;
NSString * price;
}
@end
@implementation StockData
@end
//
// ViewController.m
// testKVO
//
// Created by huangbo on 13-11-28.
// Copyright (c) 2013年 tencent. All rights reserved.
//
#import "ViewController.h"
#import "DataModel.h"
@interfaceViewController ()
{
StockData *stockForKVO;
UILabel *myLabel;
UILabel *myLabel2;
}
@end
@implementation ViewController
//2.定义此model为Controller的属性,实例化它,监听它的属性,并显示在当前的View里边
- (void)viewDidLoad
{
[superviewDidLoad];
stockForKVO = [[StockDataalloc] init];
[stockForKVOsetValue:@"searph"forKey:@"stockName"];
[stockForKVOsetValue:@"10.0"forKey:@"price"];
[stockForKVOaddObserver:selfforKeyPath:@"price"options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOldcontext:NULL];
myLabel = [[UILabelalloc]initWithFrame:CGRectMake(100, 100, 100, 30 )];
myLabel.textColor = [UIColorredColor];
myLabel.text = [stockForKVOvalueForKey:@"price"];
[self.viewaddSubview:myLabel];
myLabel2 = [[UILabelalloc]initWithFrame:CGRectMake(100, 200, 100, 30 )];
myLabel2.textColor = [UIColorredColor];
myLabel2.text = [stockForKVOvalueForKey:@"price"];
[self.viewaddSubview:myLabel2];
UIButton * b = [UIButtonbuttonWithType:UIButtonTypeRoundedRect];
b.frame = CGRectMake(100,10, 100, 30);
[b addTarget:selfaction:@selector(buttonAction) forControlEvents:UIControlEventTouchUpInside];
[self.viewaddSubview:b];
}
//3.当点击button的时候,调用buttonAction方法,修改对象的属性
-(void) buttonAction
{
[stockForKVOsetValue:@"20.0"forKey:@"price"];
}
//4. 实现回调方法
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if([keyPath isEqualToString:[NSStringstringWithFormat:@"%@",@"price"]])
{
myLabel.text = [stockForKVOvalueForKey:@"price"];
myLabel2.text = [NSStringstringWithFormat:@"%.1f", [[stockForKVOvalueForKey:@"price"] floatValue]*2];
}
}
//5.增加观察与取消观察是成对出现的,所以需要在最后的时候,移除观察者
- (void)dealloc
{
[superdealloc];
[stockForKVOremoveObserver:selfforKeyPath:@"price"];
[stockForKVOrelease];
}
/*四,小结
KVO这种编码方式使用起来很简单,很适用与datamodel修改后,
引发的UIVIew的变化这种情况,
就像上边的例子那样,当更改属性的值后,监听对象会立即得到通知*/
//hb
/*
kvo的思想是将类和控件绑定在一起,通过改变类变量的值改变控件的属性
机制是,通过改变属性后监听对象会立即得到通知
*/
- (void)didReceiveMemoryWarning
{
[superdidReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end