Maybe everyone is - (id)valueForKeyPath:(NSString *)keyPath
not very familiar with the method. In fact, this method is very powerful, for example:
NSArray *array = @[@"name", @"w", @"aa", @"jimsa"];NSLog(@"%@", [array valueForKeyPath:@"uppercaseString"]);
Output
(NAME,W,AA,JIMSA)
The equivalent of each member of the array executes the uppercaseString
method and then returns the returned object as a new array. Since the method can be used uppercaseString
, then other methods of nsstring, such as
[array valueForKeyPath:@"length"]
Returns an array of the components of each string length. As long as you can think of the member instance method can be so used.
If you think this method is a bit of a function, it's wrong. Or to give a concrete example
Fast calculation of array summation, mean, maximum, minimum for nsnumber arrays
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"];
Or specify the output type
NSNumber *sum = [array valueForKeyPath:@"@sum.floatValue"]; NSNumber *avg = [array valueForKeyPath:@"@avg.floatValue"]; NSNumber *max = [array valueForKeyPath:@"@max.floatValue"]; NSNumber *min = [array valueForKeyPath:@"@min.floatValue"];
Eliminate duplicate data
NSArray *array = @[@"name", @"w", @"aa", @"jimsa", @"aa"]; NSLog(@"%@", [array valueForKeyPath:@"@distinctUnionOfObjects.self"]);
Print
(Name, W, JIMSA, AA)
Quickly find the value of the corresponding key pair for the nsdictionary array
NSArray *array = @[@{@"name": @"cookeee",@"code": @1}, @{@"name": @"jim",@"code": @2}, @{@"name": @"jim",@"code": @1}, @{@"name": @"jbos",@"code": @1}];NSLog(@"%@", [array valueForKeyPath:@"name"]);
An array of values directly from the key in the dictionary, which is name
obviously easier to add to the new array than the loop value
(cookeee,jim,jim,jbos)
Also can be nested use, first eliminate name
the corresponding value of the duplicate data and then take the value
NSArray *array = @[@{@"name": @"cookeee",@"code": @1}, @{@"name": @"jim",@"code": @2}, @{@"name": @"jim",@"code": @1}, @{@"name": @"jbos",@"code": @1}]; NSLog(@"%@", [array valueForKeyPath:@"@distinctUnionOfObjects.name"]);
Print (Cookeee, Jim, Jbos)
Change the color of Uitextfiedl's placeholder
[searchField setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];
It's - (void)drawPlaceholderInRect:(CGRect)rect;
a lot easier than rewriting.
The use of the
Valueforkeypath (this article is to copy someone else's article, because can not be reproduced, and feel well written, so copied, I hope the author do not take offense)