Hi I have an NSMutableDictionary filled with values being NSNumbers. I would like to create a function that returns the highest NSNumber value and its corresponding key in the NSMutableDictionary while ignoring one key("Not Specified")? Does this have to be done with sorting or can you filter through some how?
Asked
Active
Viewed 470 times
0
-
Have you tried a predicate? http://stackoverflow.com/questions/16556905/filtering-nsdictionary-with-predicate – Afonso Tsukamoto Apr 17 '14 at 21:19
2 Answers
0
I'd go with something like, if it were in multiple steps:
NSMutableDictionary *slimDictionary = [originalDictionary mutableCopy];
[slimDictionary removeObjectForKey:@"Not Specified"];
NSNumber *maxValue = [[slimDictionary allValues] valueForKeyPath:@"@max.self"];
NSArray *allKeys = [slimDictionary allKeysForObject:maxValue];
// just return allKeys[0] if you know that there are definitely not multiple
// keys with the same value; otherwise do something deterministically to pick
// your most preferred key

Tommy
- 99,986
- 12
- 185
- 204
0
You could simply enumerate the dictionary once and keep track of the largest value together with the corresponding key:
NSDictionary *dict = @{@"a": @1, @"b": @2, @"Not Specified": @3};
__block NSString *highKey;
__block NSNumber *highVal;
[dict enumerateKeysAndObjectsUsingBlock:^(NSString *key, NSNumber *val, BOOL *stop) {
if (highVal == nil || [val compare:highVal] == NSOrderedDescending) {
if (![key isEqualToString:@"Not Specified"] ) {
highKey = key;
highVal = val;
}
}
}];
NSLog(@"key: %@, val: %@", highKey, highVal);
// Output: key: b, val: 2

Martin R
- 529,903
- 94
- 1,240
- 1,382
-
1For more efficiency, I'd first check whether the new value would be the highest, and then check for "Not Specified". If you have 1000 items in the dictionary, you might find a new highest value maybe 10 times, so you'd check for "Not Specified" 10 times, instead of 1000 times. – gnasher729 Apr 17 '14 at 21:39
-
@gnasher729: Good suggestion, I have updated the answer accordingly. Thanks for the feedback. – Martin R Apr 17 '14 at 21:43