1、valueForKeyPath可以获取数组中的最小值、最大值、平均值、求和。代码如下:
NSArray *array = @[@10, @23, @43, @54, @7, @17, @5];
+ (NSString *)caculateArray:(NSArray *)array
{
CGFloat sum = [[array valueForKeyPath:@"@sum.floatValue"] floatValue];
CGFloat avg = [[array valueForKeyPath:@"@avg.floatValue"] floatValue];
CGFloat max =[[array valueForKeyPath:@"@max.floatValue"] floatValue];
CGFloat min =[[array valueForKeyPath:@"@min.floatValue"] floatValue];
NSLog(@"%fn%fn%fn%f",sum,avg,max,min);
return [NSString stringWithFormat:@"%f",sum];
}
2、valueForKeyPath可以获取数组中相同key的元素
如下所示:
NSArray *arr = @[@{@"city":@"beijing",@"person":@{@"name":@"zhangsan"}},@{@"city":@"chengdu"}];
[arr valueForKeyPath:@"city"] 可以获取到city数组 @[@"beijing",@"chengdu"]
3、valueForKeyPath 可以使用. 来一层一层向下索引,当多个字典层级时,取子层级中的属性就非常简单了
NSDictionary *dict1 = @{@"dict1":@{@"dict2":@{@"name":@"lishi",@"info":@{@"age":@"12"}}}};
id res = [dict1 valueForKeyPath:@"dict1.dict2.name"];//(http://dict1.dict2.name/)
NSLog(@"res = %@",res);// 输出lishi
4、删除重复的数据
NSArray *array = @[@"qq", @"wechat", @"qq", @"msn", @"wechat"];
NSArray *deleltNewA = [array valueForKeyPath:@"@distinctUnionOfObjects.self"];
NSLog(@"deleltNewA = %@",deleltNewA);// 输出( qq, wechat, msn)
5、嵌套使用(先删除对应值的重复数据再取值)
NSArray *array = @[@{@"name" : @"xiaoming",
@"code" : @1},
@{@"name": @"judy",
@"code" : @2},
@{@"name": @"judy",
@"code" : @3},
@{@"name": @"xiaohua",
@"code" : @4}];
NSArray *deleltNewA = [array valueForKeyPath:@"@distinctUnionOfObjects.name"];
NSLog(@"deleltNewA = %@",deleltNewA);// 输出(judy, xiaohua, xiaoming);
6、改变 UITextfield 的 placeholder 的颜色
[addressTextField setValue:[UIColor redColor] forKeyPath:@”_placeholderLabel.textColor”];
比起重写 - (void)drawPlaceholderInRect:(CGRect)rect; 要方便太多!