obj-c编程16:键值编码(KVC)

    我们可以借助obj-c中的键值编码(以后简称KVC,Key-Value Coding)来存取类的属性,通过指定所要访问的属性名字符串标示符,可以使用存取器方法来获取或设置类的属性。下面的例子,借助于KVC的功能读取和设置了类Son实例的属性i:

#import <Foundation/Foundation.h>

#define msg(...) NSLog(__VA_ARGS__)
#define mki(x) [NSNumber numberWithInt:x]

@interface Son:NSObject{
	NSArray *ary;
	NSNumber *i;
}
	@property NSArray *ary;
	@property NSNumber *i;
@end

@implementation Son
	@synthesize ary,i;

	-(id)init{
		return [self init:0];
	}

	-(id)init:(int)i_v{
		self = [super init];
		if(self){
			ary = [NSArray arrayWithObjects:mki(1),mki(2),mki(10),\
				mki(100),nil];
			i = [NSNumber numberWithInt:i_v];
		}
		return self;
	}
@end

int main(int argc,char *argv[])
{
	@autoreleasepool{
		Son *son = [[Son alloc] init];
		[son setValue:mki(1001) forKey:@"i"];
		msg(@"%@",[son valueForKey:@"i"]);
		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"];

除了遍历对象关系以外,我们还可以访问一些操作对象集合的函数,比如求平均数等等:

obj-c编程16:键值编码(KVC)

下面实际看一个例子

#import <Foundation/Foundation.h>

#define msg(...) NSLog(__VA_ARGS__)
#define mki(x) [NSNumber numberWithInt:x]

@interface Son:NSObject{
	NSArray *ary;
	NSNumber *i;
}
	@property NSArray *ary;
	@property NSNumber *i;
@end

@implementation Son
	@synthesize ary,i;

	-(id)init{
		return [self init:0];
	}

	-(id)init:(int)i_v{
		self = [super init];
		if(self){
			ary = [NSArray arrayWithObjects:mki(1),mki(2),mki(10),\
				mki(100),nil];
			i = [NSNumber numberWithInt:i_v];
		}
		return self;
	}
@end

int main(int argc,char *argv[])
{
	@autoreleasepool{
		Son *son = [[Son alloc] init];
		[son setValue:mki(1001) forKey:@"i"];
		msg(@"%@",[son valueForKey:@"i"]);
		msg(@"%@",[son valueForKeyPath:@"ary.@count"]);

		Son *son0 = [[Son alloc] init:11];
		Son *son1 = [[Son alloc] init:200];
		Son *son2 = [[Son alloc] init:25];

		NSArray *ary = [NSArray arrayWithObjects:son,son0,son1,son2,nil];
		msg(@"avg:%@",[ary valueForKeyPath:@"@avg.i"]);
		msg(@"sum:%@",[ary valueForKeyPath:@"@sum.i"]);

	}
	return 0;
}

运行结果如下:

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


上一篇:构建高可用服务器之二 Keepalive参数详解


下一篇:谈谈大数据采集和常见问题