valueForKeyPath 方法的使用
2015-06-27 16:34
477 查看
可能大家对
其实这个方法非常的强大,举个例子:
输出
相当于数组中的每个成员执行了
返回每个字符串长度的组成的数组。只要你能想到的成员实例方法都可以这么用。
如果你觉得这个方法就这么点功能,那就错了。还是举具体的例子
或者指定输出类型
(
name,
w,
jimsa,
aa
)
直接得到字典中
同样可以嵌套使用,先剔除
打印
(
cookeee,
jim,
jbos
)
比起重写
- (id)valueForKeyPath:(NSString *)keyPath方法不是很了解。
其实这个方法非常的强大,举个例子:
NSArray *array = @[@"name", @"w", @"aa", @"jimsa"]; NSLog(@"%@", [array valueForKeyPath:@"uppercaseString"]);
输出
( NAME, W, AA, JIMSA )
相当于数组中的每个成员执行了
uppercaseString方法,然后把返回的对象组成一个新数组返回。既然可以用
uppercaseString方法,那么NSString的其他方法也可以,比如
[array valueForKeyPath:@"length"]
返回每个字符串长度的组成的数组。只要你能想到的成员实例方法都可以这么用。
如果你觉得这个方法就这么点功能,那就错了。还是举具体的例子
对NSNumber数组快速计算数组求和、平均数、最大值、最小值
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"];
或者指定输出类型
NSNumber *sum = [array valueForKeyPath:@"@sum.floatValue"]; NSNumber *avg = [array valueForKeyPath:@"@avg.floatValue"]; NSNumber *max = [array valueForKeyPath:@"@max.floatValue"]; NSNumber *min = [array valueForKeyPath:@"@min.floatValue"];
剔除重复数据
NSArray *array = @[@"name", @"w", @"aa", @"jimsa", @"aa"]; NSLog(@"%@", [array valueForKeyPath:@"@distinctUnionOfObjects.self"]);
打印
(name,
w,
jimsa,
aa
)
对NSDictionary数组快速找出相应key对的值
NSArray *array = @[@{@"name" : @"cookeee",@"code" : @1}, @{@"name": @"jim",@"code" : @2}, @{@"name": @"jim",@"code" : @1}, @{@"name": @"jbos",@"code" : @1}]; NSLog(@"%@", [array valueForKeyPath:@"name"]);
直接得到字典中
namekey对应的值组成的数组,显然比循环取值再加入到新数组中方便快捷
( cookeee, jim, jim, jbos )
同样可以嵌套使用,先剔除
name对应值的重复数据再取值
NSArray *array = @[@{@"name" : @"cookeee",@"code" : @1}, @{@"name": @"jim",@"code" : @2}, @{@"name": @"jim",@"code" : @1}, @{@"name": @"jbos",@"code" : @1}]; NSLog(@"%@", [array valueForKeyPath:@"@distinctUnionOfObjects.name"]);
打印
(
cookeee,
jim,
jbos
)
改变UITextfiedl的placeholder的颜色
[searchField setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];
比起重写
- (void)drawPlaceholderInRect:(CGRect)rect;要方便很多
相关文章推荐
- PowerBuilder9.0自动检测注册ASA8.0
- 下载:Windows 10 Build 10154默认新壁纸
- Builder模式在Java中的应用(转)
- UIImageView
- UIButton 导航栏属性
- UIView的layoutSubviews和drawRect方法何时调用
- 如何自己编写一个easyui插件续
- UIImageView UIButton之间的区别
- xcode7 UI 测试
- 求出最长非降子序列的长度--LIS:longest increasing subsequence
- UIView的属性方法解释(全)
- iOS开发之使用UIView-Positioning简化页面布局
- 【后缀自动机】 CodeForces 235C Cyclical Quest
- AndroidのBuild工具之Ant动手实践
- AndroidのUI体验之上拉下拉
- AndroidのUI体验之ImmersiveMode沉浸模式
- AndroidのUI布局之layout weight
- STM32F030系列UID
- iOS开发之使用UIView-Positioning简化页面布局
- 黑马程序员--Java学习日记之GUI(图形化用户界面编程)