- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
//1.KVC的使用
// Key Value Coding的缩写, 表示键值编码
//作用: 通过字符串标示的方式访问对象的property和实例变量
//项目中使用: 使用KVC实现JSON中字典到model的转换
Car *car = [[Car alloc] init];
car.type = @"BMW";
car.speed = 250;
NSLog(@"type = %@,speed=%f",car.type,car.speed);
//kvc 访问属性一种方式(特殊使用字符串做key)
//key: 属性名可以做key, 实例变量名也可以做key
[car setValue:@"Mini" forKey:@"type"];
NSLog(@"type=%@",[car valueForKey:@"type"]);
//修改基本类型, 传入的是 NSNumber
[car setValue:@(100) forKey:@"speed"];
NSLog(@"speed = %f",[[car valueForKey:@"speed"] doubleValue]);
[car setValue:@(3.14) forKey:@"_num"];
[car show];
//注意: 如果key不存在, 则抛出异常
//解决: 重新实现 setValue:forUndefinedKey:
//1.2 KeyPath的使用
Engine *engine = [[Engine alloc] init];
car.engine = engine;
//设置car的engine的power属性
[car setValue:@(300) forKeyPath:@"engine.power"];
NSLog(@"power = %f",[[car valueForKeyPath:@"engine.power"] doubleValue]);
//1.3 字典和对象转化
NSDictionary *carDict = @{@"type":@"QQ",
@"speed":@"180"};
[car setValuesForKeysWithDictionary:carDict];
NSLog(@"type = %@,speed=%f",car.type,car.speed);
//2.KVO的使用
// Key Value Observer 键值监听
//作用: 监控某个对象的某个属性的变化
//实例: 车对象, 它的speed属性变化了, 仪表盘显示速度
newCar = [[Car alloc] init];
newCar.speed = 0;
//监控
//作用: 一旦speed变化了, 执行self中指定方法
[newCar addObserver:self forKeyPath:@"speed" options:NSKeyValueObservingOptionOld|NSKeyValueObservingOptionNew context:nil];
//模拟启动
newCar.speed = 50;
newCar.speed = 100;
newCar.speed = 120;
newCar.speed = 120;
newCar.speed = 120;
}
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
static double preSpeed = 0;
//显示新的速度
double speed = [[object valueForKeyPath:keyPath] doubleValue];
if(preSpeed != speed)
{
NSLog(@"speed = %f",speed);
}
preSpeed = speed;
}
-(void)dealloc
{
[newCar removeObserver:self forKeyPath:@"speed"];
}