SoFunction
Updated on 2025-04-13

Common usage of valueForKeyPath in iOS

1. valueForKeyPath can get the minimum value, maximum value, average value, 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:@"@"] floatValue];
  CGFloat avg = [[array valueForKeyPath:@"@"] floatValue];
  CGFloat max =[[array valueForKeyPath:@"@"] floatValue];
  CGFloat min =[[array valueForKeyPath:@"@"] floatValue];
  NSLog(@"%fn%fn%fn%f",sum,avg,max,min);
  return [NSString stringWithFormat:@"%f",sum];
}

2. valueForKeyPath can get elements of the same key in the array

As shown below:

NSArray *arr = @[@{@"city":@"beijing",@"person":@{@"name":@"zhangsan"}},@{@"city":@"chengdu"}];
[arr valueForKeyPath:@"city"] Can be obtainedcityArray @[@"beijing",@"chengdu"]

3. valueForKeyPath can be used. Index down layer by layer. When multiple dictionary levels are used, it is very simple to take attributes in the sub-level.

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

4. Delete duplicate data

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

5. Nested use (first delete the duplicate data of the corresponding value and then get the value)

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”];
Compared to rewrite - (void)drawPlaceholderInRect:(CGRect)rect; Too convenient!

Summarize

The above is the commonly used usage of valueForKeyPath in iOS introduced to you by the editor. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support for my website!