Common usage of valueForKeyPath in iOS


1. ValueForKeyPath can get the minimum, maximum, average and sum in the array. The code is as follows:

NSArray *array = @[@10, @23, @43, @54, @7, @17, @5];

+ (NSString *)caculateArray:(NSArray *)array
  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];
  return [NSString stringWithFormat:@"%f",sum];

2. ValueForKeyPath can retrieve elements of the same key in an array

As follows:

NSArray *arr = @[@{@"city":@"beijing",@"person":@{@"name":@"zhangsan"}},@{@"city":@"chengdu"}];
[arr value ForKeyPath:@ "city"] you can get the city array @[@ "beijing",@ "chengdu"]

3. ValueForKeyPath can be used. To index one layer at a time, it is very simple to select attributes in the sub-level when there are multiple dictionary levels.

NSDictionary *dict1 = @{@"dict1":@{@"dict2":@{@"name":@"lishi",@"info":@{@"age":@"12"}}}};
id res = [dict1 valueForKeyPath:@""];//(
NSLog (@ "res =%@", res);//Output Lishi

4. Delete duplicate data

NSArray *array = @[@"qq", @"wechat", @"qq", @"msn", @"wechat"];
NSArray *deleltNewA = [array valueForKeyPath:@"@distinctUnionOfObjects.self"];
NSLog (@ "deleltNewA =%@", deleltNewA); // Output (qq, wechat, msn)

5. Nested usage (first delete duplicate data of corresponding values and then take values)

NSArray *array = @[@{@"name" : @"xiaoming",
         @"code" : @1},
         @{@"name": @"judy",
         @"code" : @2},
         @{@"name": @"judy",
         @"code" : @3},
         @{@"name": @"xiaohua",
         @"code" : @4}];
NSArray *deleltNewA = [array valueForKeyPath:@""];
NSLog (@ "deleltNewA =%@", deleltNewA);// output (judy, xiaohua, xiaoming);

6. Change the color of the placeholder of UITextfield

[addressTextField setValue:[UIColor redColor] forKeyPath:@”_placeholderLabel.textColor”];
It's much more convenient than rewriting -(void) drawPlaceholder InRect:(CGRect) rect!


The above is the common usage of value ForKey Path in iOS introduced by Editor Xiaobian. I hope it will be helpful to you. If you have any questions, please leave a message for me, and Editor Xiaobian will reply to you in time. Thank you very much for your support to developpaer.