现在的位置: 首页 > 综合 > 正文

Object-c学习笔记十七—–键/值编码

2017年10月25日 ⁄ 综合 ⁄ 共 1725字 ⁄ 字号 评论关闭

Cocoa提供的一种特性,将键/值编码称为KVC。

键/值编码中的基本调用包括-valueForKey:和-setValue:forkey:。

NSString *name=[car valueForKey:@"name"];

NSLog(@"%@",name);

这相当于一个get方法。当使用ValueForKey时,它自动将标量值(int,float和struct)放入NSNumber或NSValue中;当使用setValueForKey时它自动将标量值从这些对象中取出。

编辑器和苹果都以下划线开都的形式保存实例变量名称,我们尽可能的不要用下划线开头形式命名。

键/值编码还支持路径。@engine.horsepower。

将前面的Car项目添加部分属性main函数修改成如下:

    Car *car =[[[Caralloc]
init]autorelease];

    car.name=@"Herbie";

    car.make=@"Honda";

    car.model=@"CRX";

    car.numberofDoors=2;

    car.modelyear=1984;

    car.mileage=110000;

    

   
for
(int i=0;i<4;i++)

    {

       AllWeatherRadial *tire;

        tire=[[AllWeatherRadialalloc]
init];      

        [car
setTire
:tire atIndex:i];

        [tire
release
];

    }

    

   
Slant6
*engine=[[[Slant6
alloc
]init]autorelease];

    car.engine=engine;

这里是键/值对使用

   NSNumber *count;

    count=[garage
valueForKeyPath
:@"cars.@count"];

   NSLog(@"we have %@ cars",count);

   
NSNumber
*sum;

sum = [garagevalueForKeyPath:@"cars.@sum.mileage"];

NSLog (@"We have a grand total of %@ miles",
sum);

NSNumber *avgMileage;

avgMileage = [garagevalueForKeyPath:
@"cars.@avg.mileage"];

NSLog (@"average is %.2f", [avgMileagefloatValue]);

NSNumber *min, *max;

min = [garagevalueForKeyPath:@"cars.@min.mileage"];

max = [garagevalueForKeyPath:@"cars.@max.mileage"];

NSLog (@"minimax: %@ / %@",
min, max);

 我们可以在这里引用一些特殊运算符来进行计算,可以计算某些特定值的总和。


但是KVC需要解析字符串来计算你需要的答案,因此速度比较慢,但是编译器不能对它进行错误检查。不能判断它是否是错误的键路径。

nil值会报一个could not set nil as the value for the key mileage错误。

所以要重写setNilValueForKey。还有一个处理未定义的键,this class is not key value coding-compliant for the key garbanzo.

添加一个可变字典

- (void) setValue: (id) value  forUndefinedKey: (NSString *) key {

if (stuff ==nil) {

stuff = [[NSMutableDictionaryalloc]
init];

}

[stuffsetValue: value
forKey: key];

}// setValueForUndefinedKey

- (id) valueForUndefinedKey:(NSString *)key {

id value = [stuffvalueForKey: key];

return (value);

}// valueForUndefinedKey

抱歉!评论已关闭.