valueForKeyPath

  - (nullable id)valueForKeyPath:(NSString *)keyPath;

1. 数组求和

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

NSArray *array = @[@13, @23, @89, @3, @4, @46, @"2"];
CGFloat sum1 = [[array valueForKeyPath:@"@sum.floatValue"] floatValue];
NSLog(@"%f", sum1); // 180

NSArray *array5 = @[@"3", @"4", @"10"];
CGFloat sum2 = [[array5 valueForKeyPath:@"@sum.floatValue"] floatValue];
NSLog(@"%f", sum2);   //17

2. 数组内字符串操作

如果一个数组是由字符串组成的,那么字符串有的属性,都可以直接对数组内所有的字符串统一进行操作,例如:uppercaseString: 全部大写

NSArray *array = @[@"aa", @"bb", @"cc"];
    
NSArray *tmp = [array valueForKeyPath:@"uppercaseString"];
    
NSLog(@"%@", tmp);
/*
(
    AA,
    BB,
    CC
)
*/

length: 获取每个字符串长度

NSArray *array = @[@"aa", @"bb", @"cc"];
NSArray *lengths = [array valueForKeyPath:@"length"];
NSLog(@"%@", lengths);
/*
(
    2,
    2,
    2
)
*/

3. 对数组内的字典相同的key取值

如果数组内包含的对象是字典,那么可以直接取出某个key的所有值:

NSArray *array1 = @[
  @{@"uid": @"id001", @"info":@{@"owner": @"zhanSan", @"code":@"001"}},
  @{@"uid": @"id002", @"info":@{@"owner": @"liSi", @"code":@"002"}},
  @{@"uid": @"id003", @"info":@{@"owner": @"wangEr", @"code":@"003"}}
  ];
    
NSArray *uids = [array1 valueForKeyPath:@"uid"];
/*(
    id001,
    id002,
    id003
)
*/

4. 数组去重

如果数组内包含重复的元素,可以直接去重:

NSArray *array2 = @[@"1", @"dd", @"ccc", @"dd", @"1", @"d", @"d"];
NSArray *rs = [array2 valueForKeyPath:@"@distinctUnionOfObjects.self"];
NSLog(@"%@", rs);
/*(
    dd,
    d,
    1,
    ccc
)
*/

5. 数组内包含字典,去重字典某字段的重复值

如果数组中包含字典,字典某些字段的值是重复的,那么可以直接取出去掉了重复值的内容:

NSArray *array3 = @[
                        @{@"name": @"zhangsan", @"age": @"1"},
                        @{@"name": @"zhangsan", @"age": @"1"},
                        @{@"name": @"lisi", @"age": @"2"}
                        ];
    
NSArray * arr = [array3 valueForKeyPath:@"@distinctUnionOfObjects.name"];
NSLog(@"%@", arr);
/*(
    zhangsan,
    lisi
)
*/

6. 多级字典嵌套取值

如果字典中包含很多层字典,可以很方便的取出最内层字典的某个值:

NSDictionary *dic = @{
                          @"key1": @{
                                  @"key2": @{
                                          @"key3": @"lisi002"
                                          }
                                  }
                          };
NSString *key = [dic valueForKeyPath:@"key1.key2.key3"];

NSLog(@"%@", key);
 // lisi002

7. 数组内模型取值

如果数组内存放的是数据模型,同样可以取出其中某个属性的值:

NSArray *array = @[@"aa", @"bb", @"cc"];
    
    NSMutableArray *peoples = [NSMutableArray arrayWithCapacity:array.count];
    for (int i = 0; i < array.count; i++) {
        People *p = [[People alloc]init];
        p.name = array[i];
        p.age = i;
        [peoples addObject:p];
    }
    
    NSArray *names = [peoples valueForKeyPath:@"name"];
    NSLog(@"%@", names);
/*(
    aa,
    bb,
    cc
)
*/

你可能感兴趣的:(valueForKeyPath)