标签:copy test odi imp pre .com 通过 tool 路径
kvc--key-value coding,健值编码
可以通过key直接访问对象属性的value的方法
kvc主要是为了让代码变的更简介明了
用的比较多的是在后台数据解析,还有访问一些没有setter,getter方法的属性
定义都在NSKeyValueCoding.h中
主要两个方法:
//key为当前类的属性名 - (id)valueForKey:(NSString *)key; //当类没有名为key的属性时会调用抛出异常,可以复写valueForUndefinedKey:方法,作处理 - (void)setValue:(id)value forKey:(NSString *)key;//当类没有名为key的属性时会调用抛出异常,可以复写- (void)setValue:(id)value forUndefinedKey:(NSString *)key:方法,作处理 //keyPath 为访问属性的路径,比如:@"person.name",person是当前类的属性,name是person类的一个属性名 - (id)valueForKeyPath:(NSString *)keyPath; - (void)setValue:(NSValue *)value forKeyPath:(NSString *)keyPath;
异常处理
- (id)valueForUndefinedKey:(NSString *)key; - (void)setValue:(id)value forUndefinedKey:(NSString *)key
代码举例:
@interface ViewController ()
@property (nonatomic, weak) NSString *viewString;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
NSLog(@"----[%@]",[self valueForKey:@"viewString"]);
NSLog(@"----[%@]",[self valueForKey:@"viewArray"]);
[self setValue:@"testForViewString" forKey:@"viewString"];
[self setValue:@"1" forKey:@"viewArray"];
}
- (void)setValue:(id)value forUndefinedKey:(NSString *)key {
NSLog(@"【warning】!!!!!!---Undefined--key[%@]--!!!!!!",key);
}
- (id)valueForUndefinedKey:(NSString *)key {
if ([key isEqualToString:@"viewArray"]) {
return @"aaaa";
}
else {
return [super valueForUndefinedKey:key];
}
}
标签:copy test odi imp pre .com 通过 tool 路径
原文地址:http://www.cnblogs.com/chenliyang/p/6554653.html