讲述了NSObject派生对象如何使用KVO。注意:成员变量名对应就是Key。
@interface AppDelegate()
@property (strong, nonatomic) NSString *stockName;
@property (assign, nonatomic) float price;
@end
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// [self setValue:@"searph" forKey:@"stockName"];
// [self setValue:@"10.0" forKey:@"price"];
[self addObserver:self forKeyPath
:@"price" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:NULL];
self.stockName = @"searph";
self.price = 10.0;
NSLog(@"%@",[self valueForKey:@"price"]);
// [self setValue:@"20.0" forKey:@"price"];
self.price = 20.0;
return YES;
}
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if([keyPath isEqualToString:@"price"])
{
NSLog(@"%@",[self valueForKey:@"price"]);
}
}
http://blog.csdn.net/yuquan0821/article/details/6646400/
网友评论