1、获取数组中的平均值,最大值,最小值,总和,代码如下:

NSArray *ary = @[@,@,@,@,@,@,@];

[self caculateArray:ary];

-(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(@"sum is \n %.f-\n-%.f-\n-%.f-\n-%.f",sum,avg,max,min);
return [NSString stringWithFormat:@"%f",sum];
}

打印如下;

ios开发之--valueForKeyPath的用法-LMLPHP

2、获取数组中相同key的元素,代码如下:

NSArray *ary1 = @[

        @{@"city":@"beijing",@"person":@{@"name":@"libojue"}},
@{@"city":@"zhengzhou"}
];
[self returnAry:ary1]; -(NSArray *)returnAry:(NSArray *)array
{
return [array valueForKeyPath:@"city"];
}

打印如下:

ios开发之--valueForKeyPath的用法-LMLPHP

3、也是最重要的,我们平常在取最里层的属性时,需要遍历然后根据index,进行取,效率低下,用valueForKeyPath的话,可以一层一层的向下索引,就很简单了,代码如下:

    NSDictionary *dict = @{
@"data":@{
@"data2":@{
@"name":@"lily",
@"info":@{
@"age":@"",
@"sex":@""
}
}
}
};
[self returndict:dict]; -(id)returndict:(NSDictionary *)dict
{
return [dict valueForKeyPath:@"data.data2.name"];
}

打印如下:

ios开发之--valueForKeyPath的用法-LMLPHP

4、去除数组里面重复的元素,代码如下;

NSArray *ary2 = @[@"a",@"a",@"b",@"a1",@"c",@"d"];
[ary2 valueForKeyPath:@"@distinctUnionOfObjects.self"];

打印如下:

ios开发之--valueForKeyPath的用法-LMLPHP

另一种方法, containsObject方法,代码如下:

NSArray *dataArray = @[
@"a",@"b",@"cc",
@"a",@"b1",@"c1",
@"a"];
NSMutableArray *listAry = [[NSMutableArray alloc]init];
for (NSString *str in dataArray) {
if (![listAry containsObject:str]) {
[listAry addObject:str];
}
}
NSLog(@"%@",listAry);

以上方法也可以去除数组里面的相同元素。

5、嵌套使用,删除书里面对应key的重复数据,然后再完成取值,代码如下:

    NSArray *ary3 = @[
@{@"name":@"jack",@"age":@""},
@{@"name":@"lucy",@"age":@""},
@{@"name":@"jack",@"age":@""},
@{@"name":@"joe",@"age":@""}
];
[ary3 valueForKeyPath:@"@distinctUnionOfObjects.name"];

打印如下:

ios开发之--valueForKeyPath的用法-LMLPHP

6、改变UITextField的placeholder的颜色,代码如下:

[self.userNameTF setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];

效果如下:

ios开发之--valueForKeyPath的用法-LMLPHP

仅做记录,上面所有方法亲测有效!

04-14 20:59