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?

有帮助吗?

解决方案

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

其他提示

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
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top