1、valueForKeyPath可以获取数组中的最小值、最大值、平均值、求和。代码如下:
NSArray *array = @[@10, @23, @43, @54, @7, @17, @5];
1
2
3
4
5
6
7
8
9
|
+ (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的元素
如下所示:
1
2
|
NSArray *arr = @[@{@ "city" :@ "beijing" ,@ "person" :@{@ "name" :@ "zhangsan" }},@{@ "city" :@ "chengdu" }];
[arr valueForKeyPath:@ "city" ] 可以获取到city数组 @[@ "beijing" ,@ "chengdu" ]
|
3、valueForKeyPath 可以使用. 来一层一层向下索引,当多个字典层级时,取子层级中的属性就非常简单了
1
2
3
|
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、删除重复的数据
1
2
3
|
NSArray *array = @[@ "qq" , @ "wechat" , @ "qq" , @ "msn" , @ "wechat" ];
NSArray *deleltNewA = [array valueForKeyPath:@ "@distinctUnionOfObjects.self" ];
NSLog(@ "deleltNewA = %@" ,deleltNewA); // 输出( qq, wechat, msn)
|
5、嵌套使用(先删除对应值的重复数据再取值)
1
2
3
4
5
6
7
8
9
10
|
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 的颜色
1
2
|
[addressTextField setValue:[UIColor redColor] forKeyPath:@”_placeholderLabel.textColor”];
比起重写 - (void)drawPlaceholderInRect:(CGRect)rect; 要方便太多!
|
总结
以上所述是小编给大家介绍的iOS中 valueForKeyPath常用用法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对服务器之家网站的支持!
原文链接:https://www.jianshu.com/p/684fbea0a4c8