KVC —— key value coding
1.字典转模型
//self.answer = dic[@"answer"];
//self.icon = dic[@"icon"];
//self.title = dic[@"title"];
//self.options = dic[@"options"];
//kvc 把字典中的值,赋给当前对象制定的属性(@"answer")[self setValue:dic[@"answer"] forKeyPath:@"answer"];//遍历字典中所有的key,并把和对象属性对应的key 赋值[self setValuesForKeysWithDictionary:dic];
2.KVC设置与取出值
BLPerson *person = [[BLPerson alloc] init];
//kvc设置值
[person setValue:@"zs" forKeyPath:@"name"];
[person setValue:@18 forKeyPath:@"age"];
//kvc取值
[person valueForKeyPath:@"name"];
[[person valueForKeyPath:@"age"] intValue];//把对象转成字典,(可能要存储到plist中)
NSDictionary *dic = [person dictionaryWithValuesForKeys:@[@"name",@"age"]]
3.KVC与数组
BLPerson *p1 = [[BLPerson alloc] init];p1.name = @"zs";
p1.age = 18;
BLPerson *p2 = [[BLPerson alloc] init];p2.name = @"ls";
p2.age = 19;
BLPerson *p3 = [[BLPerson alloc] init];p3.name = @"ww";
p3.age = 16;
NSArray *persons = @[p1,p2,p3];//取出数组中所有人的名字
//方法1 循环 取出
//方法2
NSArray *names = [persons valueForKeyPath:@"name"];
4.KVC 多级KeyPath
BLPerson *p1 = [[BLPerson alloc] init];
p1.name = @"zs";
p1.age = 18;
BLBook *book = [[BLBook alloc] init];
book.name = @"金瓶梅";
p1.book= book;
//根据person获取book的名字
//1
[p1.book valueForKeyPath:@"name"];
//2
//NSString *name = p1.book.name;
//3 区分大小写
NSString *name = [p1 valueForKeyPath:@"book.name"];