原文链接:obj-c编程16:键值编码(KVC)
我们可以借助obj-c中的键值编码(以后简称KVC,Key-Value Coding)来存取类的属性,通过指定所要访问的属性名字符串标示符,可以使用存取器方法来获取或设置类的属性。下面的例子,借助于KVC的功能读取和设置了类Son实例的属性i:
1 #import <Foundation/Foundation.h> 2 3 #define msg(...) NSLog(__VA_ARGS__) 4 #define mki(x) [NSNumber numberWithInt:x] 5 6 @interface Son:NSObject{ 7 NSArray *ary; 8 NSNumber *i; 9 } 10 @PRoperty NSArray *ary; 11 @property NSNumber *i; 12 @end 13 14 @implementation Son 15 @synthesize ary,i; 16 17 -(id)init{ 18 return [self init:0]; 19 } 20 21 -(id)init:(int)i_v{ 22 self = [super init]; 23 if(self){ 24 ary = [NSArray arrayWithObjects:mki(1),mki(2),mki(10),\ 25 mki(100),nil]; 26 i = [NSNumber numberWithInt:i_v]; 27 } 28 return self; 29 } 30 @end 31 32 int main(int argc,char *argv[]) 33 { 34 @autoreleasepool{ 35 Son *son = [[Son alloc] init]; 36 [son setValue:mki(1001) forKey:@"i"]; 37 msg(@"%@",[son valueForKey:@"i"]); 38 msg(@"%@",[son valueForKeyPath:@"ary.@count"]);
运行结果如下:
apple@kissAir: objc_src$clang -fobjc-arc -framework Foundation k.m -o k apple@kissAir: objc_src$./k 2014-07-06 15:51:56.098 k[1386:507] 1001
KVC其中有KeyPath的概念,比如类Baba中有一个属性名为son,其是Son的对象;而类Son中也有属性NSString name,这时我们可以使用KeyPath的语法,像遍历树一样找到最终的属性name:
[baba valueForKeyPath:@"son.name"];
[baba setValue:@"tom" forKeyPath:@"son.name"];
除了遍历对象关系以外,我们还可以访问一些操作对象集合的函数,比如求平均数等等:
下面实际看一个例子
1 #import <Foundation/Foundation.h> 2 3 #define msg(...) NSLog(__VA_ARGS__) 4 #define mki(x) [NSNumber numberWithInt:x] 5 6 @interface Son:NSObject{ 7 NSArray *ary; 8 NSNumber *i; 9 } 10 @property NSArray *ary; 11 @property NSNumber *i; 12 @end 13 14 @implementation Son 15 @synthesize ary,i; 16 17 -(id)init{ 18 return [self init:0]; 19 } 20 21 -(id)init:(int)i_v{ 22 self = [super init]; 23 if(self){ 24 ary = [NSArray arrayWithObjects:mki(1),mki(2),mki(10),\ 25 mki(100),nil]; 26 i = [NSNumber numberWithInt:i_v]; 27 } 28 return self; 29 } 30 @end 31 32 int main(int argc,char *argv[]) 33 { 34 @autoreleasepool{ 35 Son *son = [[Son alloc] init]; 36 [son setValue:mki(1001) forKey:@"i"]; 37 msg(@"%@",[son valueForKey:@"i"]); 38 msg(@"%@",[son valueForKeyPath:@"ary.@count"]); 39 40 Son *son0 = [[Son alloc] init:11]; 41 Son *son1 = [[Son alloc] init:200]; 42 Son *son2 = [[Son alloc] init:25]; 43 44 NSArray *ary = [NSArray arrayWithObjects:son,son0,son1,son2,nil]; 45 msg(@"avg:%@",[ary valueForKeyPath:@"@avg.i"]); 46 msg(@"sum:%@",[ary valueForKeyPath:@"@sum.i"]); 47 48 } 49 return 0; 50 }
运行结果如下:
apple@kissAir: objc_src$./k 2014-07-06 15:51:56.098 k[1386:507] 1001 2014-07-06 15:51:56.100 k[1386:507] 4 2014-07-06 15:51:56.100 k[1386:507] avg:309.25 2014-07-06 15:51:56.101 k[1386:507] sum:1237