参考文章:http://blog.csdn.net/yuquan0821/article/details/6646400
一,概述
KVO,即:Key-Value Observing,它提供一种机制,当指定的对象的属性被修改后,则对象就会接受到通知。简单的说就是每次指定的被观察的对象的属性被修改后,KVO就会自动通知相应的观察者了。
二,使用方法
系统框架已经支持KVO,所以程序员在使用的时候非常简单。
1. 注册,指定被观察者的属性,
2. 实现回调方法
3. 移除观察
三,实例:
假设一个场景,股票的价格显示在当前屏幕上,当股票价格更改的时候,实时显示更新其价格。
1.定义DataModel,
- @interface StockData : NSObject {
- NSString * stockName;
- float price;
- }
- @end
- @implementation StockData
- @end
2.定义此model为Controller的属性,实例化它,监听它的属性,并显示在当前的View里边
- - (void)viewDidLoad
- {
- [super viewDidLoad];
- stockForKVO = [[StockData alloc] init];
- [stockForKVO setValue:@"searph" forKey:@"stockName"];
- [stockForKVO setValue:@"10.0" forKey:@"price"];
- [stockForKVO addObserver:self forKeyPath:@"price" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:NULL];
- myLabel = [[UILabel alloc]initWithFrame:CGRectMake(100, 100, 100, 30 )];
- myLabel.textColor = [UIColor redColor];
- myLabel.text = [stockForKVO valueForKey:@"price"];
- [self.view addSubview:myLabel];
- UIButton * b = [UIButton buttonWithType:UIButtonTypeRoundedRect];
- b.frame = CGRectMake(0, 0, 100, 30);
- [b addTarget:self action:@selector(buttonAction) forControlEvents:UIControlEventTouchUpInside];
- [self.view addSubview:b];
- }
3.当点击button的时候,调用buttonAction方法,修改对象的属性
- -(void) buttonAction
- {
- [stockForKVO setValue:@"20.0" forKey:@"price"];
- }
4. 实现回调方法
- -(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
- {
- if([keyPath isEqualToString:@"price"])
- {
- myLabel.text = [stockForKVO valueForKey:@"price"];
- }
- }
5.增加观察与取消观察是成对出现的,所以需要在最后的时候,移除观察者
- - (void)dealloc
- {
- [super dealloc];
- [stockForKVO removeObserver:self forKeyPath:@"price"];
- [stockForKVO release];
- }
四,小结
KVO这种编码方式使用起来很简单,很适用与datamodel修改后,引发的UIVIew的变化这种情况,就像上边的例子那样,当更改属性的值后,监听对象会立即得到通知。
最近研究了一下子KVC和KVO,KVC:即Key-Value-Coding 而KVO:即Key-Value-Observer
KVC是针对NSObject的子类,因为它的实现是由于其括展类NSObject(NSKeyValueCoding),实现了
- (void)setValue:(id)value forKey:(NSString *)key;
- (id)valueForKey:(NSString *)key;这两个方法的原因。
还有一个说清楚点就是上面的两个方法不光针对属性,对于类中的对象型变量同样适用。
而KVO也差不多,它是由于NSObject(NSKeyValueObserverRegistration)和NSObject(NSKeyValueObserving)的原因,用它可以实现回调功能下面是我写的,下面的例子我将其融合在一起
- #import "BIDViewController.h"
- #import "FirstViewController.h"
- @interface BIDViewController ()
- {
- FirstViewController* first;
- }
- @end
- @implementation BIDViewController
- - (void)viewDidLoad
- {
- [super viewDidLoad];
- // Do any additional setup after loading the view, typically from a nib.
- first=[[FirstViewController alloc] init];
- //观察FirstViewController中的变量name
- [first addObserver:self forKeyPath:@"name" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:NULL];
- }
- - (void)didReceiveMemoryWarning
- {
- [super didReceiveMemoryWarning];
- // Dispose of any resources that can be recreated.
- }
- - (IBAction)clicked:(UIButton *)sender {
- [self presentViewController:first animated:YES completion:^{}];
- }
- //如果FirstViewController中的变量name的值变化执行下面
- -(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
- {
- if([keyPath isEqualToString:@"name"])
- {
- NSLog(@"observer name is %@",[first valueForKey:@"name"]);
- }
- }
- -(void)dealloc
- {
- [self removeObserver:first forKeyPath:@"name"];
- [first release];
- [super dealloc];
- }
- @end
- #import <UIKit/UIKit.h>
- @interface FirstViewController : UIViewController
- {
- NSString* name;
- }
- - (IBAction)clicked:(id)sender;
- - (IBAction)otherClicked:(id)sender;
- @end
- #import "FirstViewController.h"
- @interface FirstViewController ()
- {
- }
- @end
- @implementation FirstViewController
- - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
- {
- self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
- if (self) {
- // Custom initialization
- }
- return self;
- }
- - (void)viewDidLoad
- {
- [super viewDidLoad];
- // Do any additional setup after loading the view from its nib.
- }
- - (void)didReceiveMemoryWarning
- {
- [super didReceiveMemoryWarning];
- // Dispose of any resources that can be recreated.
- }
- - (IBAction)clicked:(id)sender {
- //当为name设值时会执行BIDViewController中的观察方法,就可进行回调了,不过其范围是比不上真正意义上的回调
- [self setValue:@"chenliang" forKey:@"name"];
- // [self dismissModalViewControllerAnimated:YES];
- }
- - (IBAction)otherClicked:(id)sender {
- NSLog(@"firstVC name is %@",[self valueForKey:@"name"]);
- }
- @end