美文网首页
valueForKeyPath 强大功能

valueForKeyPath 强大功能

作者: JW_T | 来源:发表于2016-08-03 14:27 被阅读192次

可能大家对- (id)valueForKeyPath:(NSString *)keyPath方法不是很了解。其实这个方法非常的强大,举个例子:

NSArray *array = @[@"num", @"wol", @"abc", @"bcd"];

NSLog(@"%@", [array valueForKeyPath:@"uppercaseString"]);

输出

(

NUM,

WOL,

ABC,

BCD

)

相当于数组中的每个成员执行了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"];

相关文章

  • valueForKeyPath 强大功能

    可能大家对- (id)valueForKeyPath:(NSString *)keyPath方法不是很了解。其实这...

  • valueForKeyPath

    - (id)valueForKeyPath:(NSString *)keyPath这个方法非常的强大,举个例子: ...

  • iOS valueForKeyPath常用用法

    iOS valueForKeyPath常用用法 iOS valueForKeyPath常用用法

  • valueForKeyPath一些强大之处

    看了一个朋友的写作,感觉挺好。 可能大家对- (id)valueForKeyPath:(NSString *)ke...

  • iOS开发中很实用的技巧

    (一)valueForKeyPath的使用 valueForKeyPath和valueForKey有一些类似,但...

  • 笔记

    数组取值 1.使用 valueForKeyPath valueForKeyPath 取到所有当前key的 valu...

  • valueForKeyPath

    可能大家对- (id)valueForKeyPath:(NSString *)keyPath方法不是很了解。 其实...

  • valueForKeyPath

    1. 数组求和 如果一个数组是由NSNumber或者数字的字符串组成的,可以直接进行进行求和: 2. 数组内字符串...

  • valueForKeyPath

    体验过OC中的: 自然也想用swift玩一把,简单的取值如下:

  • valueForKeyPath

    数据操作 确保操作的属性为数字类型,否则运行时刻错误。 对象操作 首先自定义一个测试类Honzon 然后分别将te...

网友评论

      本文标题:valueForKeyPath 强大功能

      本文链接:https://www.haomeiwen.com/subject/lebqsttx.html