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];
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"];
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 int
s to NSInteger
s, just in case somebody wants to use this code on both iOS and OS X.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With