KVC:
可以通过字符串描述来更改对象状态,这种方式称为键值编码(KVC)。
KVC提供了一种在运行时而非编译时动态访问对象属性与实例变量的方法。
KVC基本调用包括setVaule:forKey:和valueForKey:两个方法。
setVaule:forKey:方法找的是setKey命名的setter,如果不存在则在对象内部查找_key或key的实例变量。valueForKey:方法同理。
如果key的getter与setter不是标准的定义,那么key的搜索会出现问题。
键路径,假设A类型有一个对象a,a中包含一个B类型的对象b,而b对象中包含一个C类型的对象c,如果a想获取或者设置c属性的内容,可以使用b.c。
使用setValue:forKeyPath:和valueForKeyPath:方法来访问键路径。包括在数组中使用KVC和KVC的运算符。常见的KVC集合运算符,@count,@sum,@avg,@min,@max
#import <Foundation/Foundation.h>
@interface Student : NSObject
{
int p1;
}
@property(copy,nonatomic)NSString *name;
@property(assign,nonatomic)int age;
@property(strong,nonatomic)NSMutableArray *courseMarr;
@end
#import "Student.h"
@interface Student ()
@end
@implementation Student
-(NSString *)description
{
return [NSString stringWithFormat:@"My name is %@, My age is %d,my p1 is %d",self.name,self.age,p1];
}
@end
#import <Foundation/Foundation.h>
#import "Student.h"
#import "Course.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
Student *stu = [[Student alloc] init];
//设置属性值
[stu setValue:@"Jhon" forKey:@"name"];
[stu setValue:@5 forKey:@"age"];
//设置实例变量值
[stu setValue:@6 forKey:@"p1"];
NSLog(@"%@",[stu description]);
NSLog(@"name:%@,age:%@",[stu valueForKey:@"name"],[stu valueForKey:@"age"]);
NSMutableArray *courseArr = [NSMutableArray arrayWithCapacity:4];
for (int i=0;i<4; i++) {
Course *c = [[Course alloc] init];
c.cName = [NSString stringWithFormat:@"%d course",i];
c.score = i + 60;
courseArr[i]=c;
}
stu.courseMarr = courseArr;
//在数组中使用KVC,键路径
NSLog(@"Course:%@",[stu valueForKeyPath:@"courseMarr.cName"]);
NSLog(@"Course:%@",[stu valueForKeyPath:@"courseMarr.score"]);
//KVC-集合运算符
NSLog(@"count=%@",[stu valueForKeyPath:@"courseMarr.@count"]);
NSLog(@"sum=%@",[stu valueForKeyPath:@"courseMarr.@sum.score"]);
NSLog(@"avg=%@",[stu valueForKeyPath:@"courseMarr.@avg.score"]);
NSLog(@"min=%@",[stu valueForKeyPath:@"courseMarr.@min.score"]);
NSLog(@"max=%@",[stu valueForKeyPath:@"courseMarr.@max.score"]);
}
return 0;
}
KVC无法对键路径进行错误检验,访问不存在的键时,报出
NSUnknownKeyException错误,程序崩溃。
KVC可以处理未定义值,避免程序崩溃。
//处理未定义键的取值方法
-(id)valueForUndefinedKey:(NSString *)key
{
return nil;
}
//处理未定义键的设置值方法
-(void)setValue:(id)value forUndefinedKey:(NSString *)key
{
}