您好我有一个NSMutableDictionary,其值为NSNumbers。我想创建一个函数,它返回NSMutableDictionary中最高的NSNumber值及其对应的键,而忽略一个键(“未指定”)?这是必须通过排序完成还是可以过滤一些方法?
答案 0 :(得分:0)
如果有多个步骤,我会选择类似的东西:
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
答案 1 :(得分:0)
您可以简单地枚举字典一次并跟踪最大字典 值与相应的键一起:
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