KVC: Key Value Coding
KVC 常用方法:
kvc的方式,给对象的方法赋值。灵活。
[p1 setValue:@"李四" forKeyPath:@"name"];
[p1 setValue:@10, forKeyPath:@"age"];
[p1 setValue:hashiqi forKeyPath:@"dog"];
NSString *value = @"tom@qq.com";
NSString *property = @"email";
[p1 setValue:value forKeyPath:property];
通过字典直接给对象赋值
字典NSDictionary中的字段,与对象的属性字段一致。
NSDictionary *bz = @{@"name":@“张三”,
@"age":@28,
@"email":@"tom@163.com",
@"dog":@{@"name": @"猫咪"}
};
[p1 setValuesForKeysWithDictionary:bz];
NSDictionary *dogDict = (NSDictionary *)p1.dog;
NSLog(@"dog --%@", dogDict[@"name"]);
通过keyPath复制。
Person *p1 = [[Person alloc] init];
Dog *dog = [[Dog alloc] init];
[p1 setValue:dog forKeyPath:@"dog"]; // 确保dog属性不为空
[p1 setValue:@18 forKeyPath:@"age"];
[p1 setValue:@"哈士奇", forKeyPath:@"dog.name"]; // @“dog.name”就是KeyPath
valueForKeyPath 获取某个属性的值。
setValueForKeyPath 设置某个属性的值。
Person *p1 = [[Person alloc] init];
p1.name = @"蓝澜";
Dog *dog1 = [[Dog alloc] init];
dog1.name = @"吉娃娃";
p1.dog = dog1;
NSString *name = [p1 valueForKeyPath:@"name"];
NSString *dogName = [p1 valueForKeyPath:@"dog.name"]; // 拿到dog的name属性。
把对象转字典。dictionaryWithValuesForKeys
Person *p1 = [[Person alloc] init];
p1.name = @"蓝澜";
Dog *chh = [[Dog alloc] init];
chh.name = @"jww";
p1.dog = chh;
// 传递属性的数组。
NSDictionary *dict = [p1 dictionaryWithValuesForKeys:@[@"name", @"age", @"email", @"dog"]];
NSLog(@"%@", dict);
NSLog(@"%@", [dict[@"dog" class]);
NSLog(@"%@", [dict[@"dog" name]); // dog是个对象
2023/06/04 周日