-(nullable id)valueForKeyPath:(NSString *)keyPath
1.数组求和
如果一个数组是由NSNumber或者数字的字符串组成的,可以获取数组最大值,最小值,平均值以及求和等等,
//求和
NSArray *array = @[@3, @"100", @47, @4, @8, @86, @"9"];
CGFloat sum = [[array valueForKeyPath:@"@sum.floatValue"] floatValue];
NSLog(@"%f",sum);//257
//最大值
CGFloat max = [[array valueForKeyPath:@"@max.floatValue"] floatValue];
NSLog(@"%f",max);//100
//最小值
CGFloat min = [[array valueForKeyPath:@"@min.floatValue"] floatValue];
NSLog(@"%f",min);//3
//平均值
CGFloat avg = [[array valueForKeyPath:@"@avg.floatValue"] floatValue];
NSLog(@"%f",avg);//36.7
2.操作数组字符串
如果一个数组是由字符串组成的,那么可以直接对数组内所有的字符串统一进行操作
lowercaseString:小写; uppercaseString:大写
NSArray *array = @[@"AA", @"BB", @"CC",@"DD"];
NSArray *temp = [array valueForKeyPath:@"lowercaseString"];
NSLog(@"%@", temp);
/**
(
aa,
bb,
cc,
dd
)
*/
length:计算长度
NSArray *array = @[@"AAaa", @"BBb", @"CCc",@"DDDDD"];
NSArray *lengths = [array valueForKeyPath:@"length"];
NSLog(@"%@", lengths);
/**
(
4,
3,
3,
5
)
*/
3.获取数组中相同key的元素
1.如果数组内包含的对象是字典,那么可以直接取出某个key的所有值:
NSArray *array = @[@{@"name":@"zhangSan",@"age":@"18",@"code":@"99"},
@{@"name":@"liSi",@"age":@"19",@"code":@"80"},
@{@"name":@"wangWu",@"age":@"17",@"code":@"59"}];
NSArray *temp = [array valueForKeyPath:@"name"];
NSLog(@"%@",temp);
/**
(
zhangSan,
liSi,
wangWu
)
*/
2.如果数组内存放的是模型,同样可以取出模型数组其中某个属性的值
NSArray *array = @[@"Tom", @"Ben", @"Swetty"];
NSMutableArray *peoples = [NSMutableArray arrayWithCapacity:array.count];
for (int i = 0; i < array.count; i++) {
People *p = [[People alloc]init];
p.name = array[i];
p.age = i;
[peoples addObject:p];
}
NSArray *names = [peoples valueForKeyPath:@"name"];
NSLog(@"%@", names);
/**
(
Tom,
Ben,
Swetty
)
*/
4.数组去重
1.如果数组内包含重复的元素,可以直接去重.
NSArray *array = @[@"qq", @"wechat", @"qq", @"msn", @"wechat"];;
NSArray *temp = [array valueForKeyPath:@"@distinctUnionOfObjects.self"];
NSLog(@"%@",temp);
/**
(
qq,
wechat,
msn
)
*/
5.数组内包含字典,去重字典某字段的重复值
如果数组中包含字典,字典相同字段的值有重复的,那么可以直接取出去掉了重复值的内容,先删除对应值的重复数据再取值
NSArray *array = @[
@{@"name": @"zhangsan", @"age": @"1"},
@{@"name": @"zhangsan", @"age": @"2"},
@{@"name": @"lisi",@"age": @"2"},
];
NSArray *temp = [array valueForKeyPath:@"@distinctUnionOfObjects.name"];
NSLog(@"%@",temp);
/**
(
zhangsan,
lisi
)
*/
6.多级字典嵌套取值
如果字典中包含很多层字典,可以很方便取出最内层字典的某个值:
NSDictionary *dic = @{
@"key1": @{
@"key2": @{
@"key3": @"zhangSan"
}
}
};
NSString *key = [dic valueForKeyPath:@"key1.key2.key3"];
NSLog(@"%@",key);
/**
zhangSan
*/
6.改变 UITextfield 的 placeholder 的颜色
比起重写 - (void)drawPlaceholderInRect:(CGRect)rect; 要方便太多!
[addressTextField setValue:[UIColor redColor] forKeyPath:@”_placeholderLabel.textColor”];
参考文献
[iOS] valueForKeyPath 使用
iOS valueForKeyPath常用用法