Objective-C日记-之KVC

KVC(Key-Value-Coding?)

1, 概述

以字符串形式向对象的实例变量或属性(Property)发送或者获得值的方法。

2,用法

a,取值

@property (readwrite,copy)NSString * name; //car.h

@synthesize name;//car.m

 现在,我想获得name的值,则可使用KVC方法

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

b,设置值

 [car setValue:@"Harlod" forKey:@"name"];

3,延伸用法

a,使用路径(字符串表达形式加点表达形式)-(void)setValue:forKeyPath

@interface Engine:NSObject <NSCopying>{

      int horsepower;

}

@end//Engine 

[car setValue:[NSNumber numberWithInt:155]

          forKeyPath:@"engine.horsepower"];

 b,对NSArray使用键值,会对数组中每一个对象来查找这个键值,并将查询结果打包返回。

如下:

NSArray *pressures=[car valueForKeyPath:@"tires.pressure"];

NSLog(@"pressures %@",pressures);

会输出如下结果:

pressures(

34,

34,

34,

34

)

4,递进用法

a,快速运算,即使用转义运算符如@count,@max,@min,@avg计算键路径左侧的结果。

如下:

@interface Garge:NSObject{

     NSString *name;

     NSMutableArray *cars;

}

@property (readwrite,copy) NSString *name;

-(void) addCar:(Car *)car;

-(void)print;

@end//Garage

 

NSNumber *count;

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

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

 

NSNumber *sum;

sum=[garage valueForKeyPath:@"cars.@sum.mileage"];

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

b,快速获取或设置(使用字典)

-dictionaryWithValuesForKeys和-setValueForKeysWithDictionary

如下(获取值):

car=[[garage valueForKeyPath:@"cars"] lastObject];//键值路径中的cars并不是Garage中的属性,但也可以作为属性路径

首先,从garage中挑选一辆车car,如上

NSArray *keys=[NSArray arrayWithObjects:@"make",@"model",@"modelYear",nil];

而后,将需要获取的属性单列出来,放入keys数组中,如上

NSDictionary *carValues=[car dictionaryWithValuesForKeys:keys];

最后,使用字典型对像存储使用-dictionaryWithValuesForKeys获取的字典值。

以下为(设置值):

NSDictionary *newValues=[NSDictionary dictionaryWithObjectsAndKeys:@"Chevy",@"make",@"Nova",@"model",[NSNumber numberWithInt:1964],@"modelYear",nil];

首先,定义一个字典

[car setValuesForKeysWithDictionary:newValues];

再次,设置car的值。

c,处理未定义的键

当我们使用valueForKey时,使用的是一个未定义的关键字,则在运行时会报错:

this class is not key value coding-compliant for the key xxxxxx.

我们在处理这类问题时,一般会采用改写-valueForUndefinedKey和-setValue:forUndefinedKey方法

在Objective-C基础教程上采用的是如下方法

c1,定义一个空的字典对象stuff.

@interface Garage:NSObject{

     NSString *name;

     NSMutableArray *cars;

     NSMutableDictionary *stuff;

}

c2,处理,设置未定义键的赋值问题,将键值对放入字典对象中

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

if(stuff=nill){

      stuff==[[NSMutableDictionary alloc]init];

}

       [stuff setValeu:value forKey:key];

}//setValueForUndefinedKey

c3,处理,获取未定义键的值,将查找重定向至字典对象

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

      id value=[stuff valueForKey:key];

      return (value);

}//valueForUndefinedKey

posted @ 2016-07-10 19:06  dbseti  阅读(271)  评论(0编辑  收藏  举报