我认为这个问题最简单的方法是使用比较器..
NSString *defaultNames[] = {@"Matt", @"Terry",@"Jessica",@"Sean",nil};
NSNumber *defaultScores[] = {@(600), @(500),@(400),@(50), nil};
NSDictionary *newScoreDict = [NSDictionary dictionaryWithObjects:defaultNames forKeys:defaultScores count:4];
NSArray *currScores = [newScoreDict keysSortedByValueUsingComparator:^NSComparisonResult(id obj1, id obj2) {
if ([obj1 integerValue] > [obj2 integerValue]) {
return NSOrderedAscending;
}else{
return NSOrderedDescending;
}}];
for (NSString *string in currScores) {
NSLog(@"%@",string);
}
试试这个.. 我注意到我无法通过使用 NSNumber 对象来达到价值,所以如果你想达到对象价值,我可以通过将你的 NSNumber 分数更改为 NSString 并在订购时将它们转换为数字来解决。你可以像下面这样使用..
NSString *defaultNames[] = {@"Matt", @"Terry",@"Jessica",@"Sean",nil};
NSString *defaultScores[] = {@"600", @"500",@"400",@"50", nil};
NSMutableDictionary *newScoreDict = [NSMutableDictionary dictionaryWithObjects:defaultScores forKeys:defaultNames count:4];
NSArray *currScores = [newScoreDict keysSortedByValueUsingComparator:^NSComparisonResult(id obj1, id obj2) {
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
NSNumber *number1 = [formatter numberFromString:obj1];
NSNumber *number2 = [formatter numberFromString:obj2];
if (number1.intValue > number2.intValue) {
return NSOrderedDescending;
}else{
return NSOrderedAscending;
}}];
for (NSString *name in currScores) {
NSLog(@"key %@ value %@",name,[newScoreDict valueForKey:name]);
}
希望能帮助到你..