valueForKeyPath的妙用(转)
可能大家对 - (id)valueForKeyPath:(NSString *)keyPath 方法不是很了解。
其实这个方法非常的强大,举个例子:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
NSArray *array = @[@"name", @"w", @"aa", @"jimsa"]; NSLog(@"%@", [array valueForKeyPath:@"uppercaseString"]); 输出 ( NAME, W, AA, JIMSA )
相当于数组中的每个成员执行了uppercaseString
方法,然后把返回的对象组成一个新数组返回。
既然可以用uppercaseString
方法,那么NSString的其他方法也可以,比如
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
[array valueForKeyPath:@"length"]
返回每个字符串长度的组成的数组。只要你能想到的成员实例方法都可以这么用。
如果你觉得这个方法就这么点功能,那就错了。还是举具体的例子,继续往下看
对NSNumber数组快速计算数组求和、平均数、最大值、最小值
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
NSArray *array = @[@1, @2, @3, @4, @10]; NSNumber *sum = [array valueForKeyPath:@"@sum.self"]; NSNumber *avg = [array valueForKeyPath:@"@avg.self"]; NSNumber *max = [array valueForKeyPath:@"@max.self"]; NSNumber *min = [array valueForKeyPath:@"@min.self"];
或者指定输出类型
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 NSNumber *sum = [array valueForKeyPath:@"@sum.floatValue"]; 2 NSNumber *avg = [array valueForKeyPath:@"@avg.floatValue"]; 3 NSNumber *max = [array valueForKeyPath:@"@max.floatValue"]; 4 NSNumber *min = [array valueForKeyPath:@"@min.floatValue"];
剔除重复数据
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 NSArray *array = @[@"name", @"w", @"aa", @"jimsa", @"aa"]; 2 NSLog(@"%@", [array valueForKeyPath:@"@distinctUnionOfObjects.self"]);
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 打印 2 3 ( 4 name, 5 w, 6 jimsa, 7 aa 8 )
对NSDictionary数组快速找出相应key对的值
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 NSArray *array = @[@{@"name" : @"cookeee",@"code" : @1}, 2 @{@"name": @"jim",@"code" : @2}, 3 @{@"name": @"jim",@"code" : @1}, 4 @{@"name": @"jbos",@"code" : @1}]; 5 NSLog(@"%@", [array valueForKeyPath:@"name"]);
直接得到字典中name
key对应的值组成的数组,显然比循环取值再加入到新数组中方便快捷
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 ( 2 cookeee, 3 jim, 4 jim, 5 jbos 6 )
同样可以嵌套使用,先剔除name
对应值的重复数据再取值
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 NSArray *array = @[@{@"name" : @"cookeee",@"code" : @1}, 2 @{@"name": @"jim",@"code" : @2}, 3 @{@"name": @"jim",@"code" : @1}, 4 @{@"name": @"jbos",@"code" : @1}]; 5 6 NSLog(@"%@", [array valueForKeyPath:@"@distinctUnionOfObjects.name"]); 7 8 打印 9 ( 10 cookeee, 11 jim, 12 jbos 13 )
改变UITextfiedl的placeholder的颜色
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 [searchField setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];
比起重写- (void)drawPlaceholderInRect:(CGRect)rect;
要方便很多
转至:http://segmentfault.com/a/1190000000526660