In the normal development process, the member variables of a class may be a custom class or other complex data type, you can use KVC to obtain the attributes, and then use KVC to obtain the attributes of the custom class, but this is cumbersome, there is a solution, that is, the keyPath** keyPath**. The common methods for using valueForKeyPath are as follows:

Uppercase the element
NSArray *spellArr=@[@"spell",@"a",@"b",@"c",@"d",@"e"];
NSLog(@"大写---%@",[spellArr valueForKeyPath:@"uppercaseString"]);

输出结果---
KeyPath[1359:72155] 大写---(
    SPELL,
    A,
    B,
    C,
    D,
    E
)
Copy the code
Various numerical calculations
NSArray *numberArr=@[@3,@10,@7,@32,@12,@6,@9]; CGFloat sum=[[numberArr valueForKeyPath:@"@sum.floatValue"]floatValue]; CGFloat avg=[[numberArr valueForKeyPath:@"@avg.floatValue"]floatValue]; CGFloat min=[[numberArr valueForKeyPath:@"@min.floatValue"]floatValue]; CGFloat max=[[numberArr valueForKeyPath:@"@max.floatValue"]floatValue]; NSLog (@ "total sum = % 2 f - mean avg = %. 2 f - min min = %. 2 - the maximum Max = % f. 2 f", sum, avg, min, Max). ---- KeyPath[1407:77817] Total sum=79.00- Average avG =11.29- Minimum min=3.00- Maximum Max =32.00Copy the code
Filter elements with the same key
NSArray *array=@[ @{ @"name":@"person", @"age":@"18" }, @{ @"name":@"haha" }, @{ @"name":@"xixi", @"height":@"180" } ]; NSLog(@" filter elements with the same key --%@",[array valueForKeyPath:@"name"]); -- KeyPath[1407:77817] Filters elements of the same key in the array --(person, haha, xixi)Copy the code
Take the multi-level neutron level attribute
NSDictionary *dic=@{ @"first":@{ @"second":@{ @"name":@"text", @"third":@{@"age":@"18"} } } }; [dic valueForKeyPath:@"first.second. Name "]); KeyPath[1407:77817] For multiple dictionary levels, text is the attribute of the sublevelCopy the code
Removing duplicate elements
NSArray *repeatArr=@[@"haha",@"xixi",@4,@"haha",@4,@"lala"]; NSLog (@ "removing repeating elements in the array -- % @", [repeatArr valueForKeyPath: @ "@ distinctUnionOfObjects. Self"]); NSSet *set = [NSSet setWithArray:repeatArr]; NSArray *setArr=[set allObjects]; KeyPath[1407:77817] removes duplicate elements from the array --(xixi, lala, haha, 4)Copy the code
Take values stored in the model hierarchy
NSMutableDictionary *dictionary=[NSMutableDictionary dictionary]; Model *model=[Model new]; model.title=@"text"; [dictionary setValue:model forKey:@"preface"]; NSString *resultPath=[dictionary valueForKeyPath:@"preface.title"]; NSLog(@" get values stored in the model hierarchy --%@",resultPath); The output -- KeyPath[1407:77817] gets the value stored in the model hierarchy --textCopy the code

  • Also attached is a DETAILED explanation of KVC