@interface FoodData : NSObject
{
NSString * foodName;
float foodPrice;
}
@end
foodData = [[FoodDataalloc]init];
[foodDataaddObserver:selfforKeyPath:@"foodName"options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOldcontext:nil];
[foodDataaddObserver:selfforKeyPath:@"foodPrice"options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOldcontext:nil];
///调用
[foodDatasetValue:@"apple"forKey:@"foodName"];
[foodDatasetValue:@"100.0"forKey:@"foodPrice"];
///响应
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if( [keyPath isEqualToString:@"foodName"])
{
NSLog(@"foodName:%@",[foodDatavalueForKey:@"foodName"]);
}
else if( [keyPath isEqualToString:@"foodPrice"])
{
NSLog(@"foodPrice:%@",[foodDatavalueForKey:@"foodPrice"]);
}
}