How to get the highest value from an NSArray containing dictionaries?

How do you get the most value from NSArray with dictionaries?

Let's say that I have an NSArray containing dictionaries with the keys "age", "name", etc. Now I want to get the record with the highest age. Is this possible with some kind of KVC magic? Or do I need to iterate over and do it "manually"?

I tried something similar to this:

int max = [[numbers valueForKeyPath:@"@max.intValue"] intValue]; 
+7
source share
2 answers

If "intValue" is not the key in your dictionary, the key path will not bring much benefit.

If this is the maximum age, you should use @"@max.age" (in the dictionary) to get it. The same applies to any other key in your dictionary.

 [myDictionary valueForKeyPath:@"@max.age"]; 

If numbers is an array of values, you can use @"@max.self" as the key path to get the highest value.

 [myArrayOfNumbers valueForKeyPath:@"@max.self"]; 
+14
source

You are almost there, you just need to specify the exact field from which you want to get the maximum value:

 NSInteger max = [[numbers valueForKeyPath:@"@max.age"] integerValue]; 

I took the liberty of changing your int to NSInteger s, just in case someone wants to use this code for both iOS and OS X.

+1
source

All Articles