iOS valueForKeyPath基本用法

1、valueForKeyPath可以获取数组中的最小值、最大值、平均值、求和。
    NSArray *array = @[@10, @23, @43, @54, @7, @17, @5];
    // 数组求和
    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(@"\n%f\n%f\n%f\n%f",sum,avg,max,min);
2、valueForKeyPath可以获取数组中相同key的元素
    NSArray *array = @[@{@"city":@"beijing",
                       @"person": @{@"name":@"zhangsan"}},
                     @{@"city":@"chengdu"}];
    NSArray *newArray = [array valueForKeyPath:@"city"];
    NSLog(@"%@",newArray);
3、valueForKeyPath 可以使用. 来一层一层向下索引,当多个字典层级时,取子层级中的属性就非常简单了
    NSDictionary *dict = @{@"dict1":@{@"dict2":@{@"name":@"lishi",@"info":@{@"age":@"12"}}}};
    id res = [dict valueForKeyPath:@"dict1.dict2.name"];//(http://dict1.dict2.name/)
    NSLog(@"res = %@",res);// 输出lishi
4、删除重复的数据
    NSArray *array = @[@"qq", @"wechat", @"qq", @"msn", @"wechat"];
    NSArray *deleltNewA = [array valueForKeyPath:@"@distinctUnionOfObjects.self"];
    NSLog(@"deleltNewA = %@",deleltNewA);// 输出( qq, wechat,  msn)
5、嵌套使用(先删除对应值的重复数据再取值)
    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);

你可能感兴趣的:(iOS valueForKeyPath基本用法)