Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the largest value from NSArray containing dictionaries?

How do you get the largest value from an NSArray with dictionaries?

Lets say I have NSArray containing dictionaries with keys "age", "name", etc. Now I want to get the record with the highest age. Is this possible with some KVC magic? Or do I have to iterate through and do it the "manual" way?

I've tried with something similar to this:

int max = [[numbers valueForKeyPath:@"@max.intValue"] intValue];
like image 685
cmd Avatar asked Jul 17 '12 12:07

cmd


2 Answers

Unless "intValue" is a key in your dictionary the key path won't do much good.

If it is the max age you are after you should use @"@max.age" (on the dictionary) to get it. The same goes for any other key in your dictionary.

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

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

[myArrayOfNumbers valueForKeyPath:@"@max.self"];
like image 111
David Rönnqvist Avatar answered Oct 12 '22 10:10

David Rönnqvist


You're nearly there, you just need to specify the exact field you want from which you want the max value:

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

I took the liberty to modify your ints to NSIntegers, just in case somebody wants to use this code on both iOS and OS X.

like image 31
Monolo Avatar answered Oct 12 '22 11:10

Monolo