转自http://www.cnblogs.com/mybkn/archive/2013/05/29/3104166.html

KVO:

在看KVO之前,有必要先了解下KVC,即,Key-Value Coding 键值对编程。通过key-value可以方便的存取数据。

具体的操作简单说就是:setValue:forKey:   valueForKey:

//book Object
//.h
#import <Foundation/Foundation.h>
@class Author;
@interface Book : NSObject{
NSString *name;
Author *author;
float price;
NSArray *relativeBooks;
}
@end
#import "Book.h"
@implementation Book
@end
Book *book = [[Book alloc] init];
[book setValue:@"iOS book" forKey:@"name"];//这里要注意实例变量的名字不要写错,写错了不会有提示
NSString *name = [book valueForKey:@"name"];
NSLog(@">> %@",name); Author *author = [[Author alloc] init];
[author setValue:@"Zhan" forKey:@"name"];
[book setValue:author forKey:@"author"]; NSString *authorName = [book valueForKeyPath:@"author.name"];
NSLog(@">> %@",authorName); [book setValue:@"" forKey:@"price"];
NSLog(@">> %@",[book valueForKey:@"price"]); Book *book1 = [[Book alloc] init];
[book1 setValue:@"" forKey:@"price"];
Book *book2 = [[Book alloc] init];
[book2 setValue:@"" forKey:@"price"]; NSArray *books = [NSArray arrayWithObjects:book1,book2,nil];
[book setValue:books forKey:@"relativeBooks"];
NSLog(@">>%@",[book valueForKeyPath:@"relativeBooks.price"]);

KVO是基于kvc实现的,采取的是观察者的模式:

    book4=[[Book alloc] init];
//增加观察者,为本类,keypath为book中的price对象,所以为price
[book4 addObserver:self forKeyPath:@"price" options:NSKeyValueObservingOptionOld|NSKeyValueObservingOptionNew context:nil];
//修改值
[book4 setValue:@"" forKey:@"price"];
//回掉方法,只要book4的值一改变就会回调这个方法

-(void) observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary *)change
context:(void *)context{
NSLog(@"cel back");
if([keyPath isEqual:@"price"]){
NSLog(@">>>>>>>price is changed");
NSLog(@"old price is %@",[change objectForKey:@"old"]);
NSLog(@"new price is %@",[change objectForKey:@"new"]);
}
}

05-23 14:37