pragma mark 获取单个值
NSString *name = [p valueForKey:@"name"];
double money = [[p valueForKey:@"money"] doubleValue];
#pragma mark 获取多层值
//NSString *PName = [p valueForKey:@"person.name"];
NSString *PName = [p valueForKeyPath:@"person.name"];
#pragma mark 模型转字典
NSDictionary *dict = [p dictionaryWithValuesForKeys:@[@"name", @"money"]];
#pragma mark 获取数组中对象的值
Person *p1 = [Person new];
p1.name = @"hh";
p1.money = 111;
Person *p2 = [Person new];
p2.name = @"ll";
p2.money = 222;
Person *p3 = [Person new];
p3.name = @"vv";
p3.money = 333;
NSArray *arr = @[p1, p2, p3];
// 如果数组中的元素都是同一种类型的数据, 可以使用KVC获取数组中所有对象的某个属性的值
NSArray *res = [arr valueForKeyPath:@"name"];
#pragma mark 运算符
id res1 = [arr valueForKeyPath:@"@avg.money"];
#pragma mark 单个值
[p setValue:@"lmj" forKey:@"name"];
#pragma mark 多层赋值
[p setValue:@"xiaoqiang" forKeyPath:@"dog.name"];
[p setValue:@(110) forKeyPath:@"dog.price"];
#pragma mark 给私有成员变量赋值
/*
// [p setValue:@"cjp" forKey:@"_name"];
// [p setValue:@(30) forKey:@"_age"];
// SEL sel = @selector(say);
// [p performSelector:sel];
// [p say];
*/
#pragma mark 字典转模型
NSDictionary *dict = @{
@"name":@"xxx",
@"money": @(998.1),
// @"score":@(100)
@"dog":@{
@"name":@"wangcai",
@"price":@(110)
}
};
// p.name = dict[@"name"];
// p.money = [dict[@"money"] doubleValue];
[p setValuesForKeysWithDictionary:dict];
网友评论