//被監控的類
@interface Person : NSObject{
NSString *name;
}
@property(retain) NSString *name; //被監控的屬性
@end
@implementation Person
@synthesize name;
@end
//觀察者
@interface KVCObserver : NSObject
{}
@end
@implementation KVCObserver
//callback
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
NSLog(@"value change! key path :%@",keyPath);
NSLog(@"object : %@",object);
NSLog(@"old value: %@",[change objectForKey: NSKeyValueChangeOldKey ]);
NSLog(@"new value: %@",[change objectForKey: NSKeyValueChangeNewKey ]);
}
@end
KVCObserver *vc = [[VCObserver alloc] init];
Person *friend = [[Person alloc] init];
friend.name = @"jack";
[friend addObserver:vc forKeyPath:@"name" options:(NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld) context:nil];
[friend setName:@"jory"]; //執行後将call 到vc