1.KVC之字典转模型
- (instancetype)initWithDict:(NSDictionary *)dict
{
self = [super init];
if (self) {
// self.answer = dict[@"answer"];
// self.icon = dict[@"icon"];
// self.title = dict[@"title"];
// self.options = dict[@"options"];
//KVC (key value coding)键值编码
//cocoa 的大招,允许间接修改对象的属性值
//第一个参数是字典的属性
//第二个参数是类的属性
// [self setValue:dict[@"answer"] forKeyPath:@"answer"];
// [self setValue:dict[@"icon"] forKeyPath:@"icon"];
// [self setValue:dict[@"title"] forKeyPath:@"title"];
// [self setValue:dict[@"options"] forKeyPath:@"options"];
//使用setValuesForKeys要求类的属性必须在字典中存在
[self setValuesForKeysWithDictionary:dict];
return self;
}
+ (instancetype)questionWithDict:(NSDictionary *)dict
{
return [[self alloc] initWithDict:dict];
}
2. 使用KVC间接修改对象属性时,系统会自动判断对象属性的类型,并完成转换
Person *p1 = [[Person alloc] init];
[p1 setValue:@"mike" forKeyPath:@"name"];
// NSNumber 基本数据类型
// NSValue 结构体
[p1 setValue:@"18" forKeyPath:@"age"];
3 .KVC按照键值路径取值时,如果对象不包含指定的键值,会自动进入对象内部,查找对象属性
列如:p1是含有name的对象,persons是拥有子元素p1和p2的数组
[p1 valueForKeyPath:@"name"] //取p1中name的值
NSArray *array = [persons valueForKeyPath:@"name"];//取p1和p2的内部属性的值,并组成数组