我正在寻找一个字典中的项目数组,然后按降序排列,以便最大值位于顶部,最小值位于底部。然而,当我的物品长度超过一位时,它似乎很难。NSArray不按数字顺序排序
我的代码是这样的:
// build a new dictionary to swap the values and keys around as my main dictionary stores these values in another way
NSMutableDictionary *newDictionary = [[NSMutableDictionary alloc] init];
for (int i = 1; i < (numberOfPlayers + 1); i++){
[newDictionary setValue:[NSString stringWithFormat:@"player%dSquareNumber", i] forKey:[NSString stringWithFormat:@"%@",[PlayerDictionary valueForKey:[NSString stringWithFormat:@"player%dSquareNumber", i]]]];
NSLog(@"value added to dictionary");
// my value should now look like "player1SquareNumber", and the key will be a number such as 8, 12, 32 etc
}
// build array to sort this new dictionary
NSArray *sortedKeys = [[newDictionary keysSortedByValueUsingSelector:@selector(compare:)] sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];
// make an array to sort based on this array
NSMutableArray *sortedValues = [NSMutableArray array];
for (NSString *key in sortedKeys){
[sortedValues addObject:[newDictionary objectForKey:key]];
}
NSLog(@"sortedValues = %@", sortedValues);
NSLog(@"sortedKeys = %@", sortedKeys);
我的排序按键理论上应该按数字顺序排列的,但我所得到的是像
10
11
18
7
8
对于我sortedArrayUsingSelector:@selector()
输出我已经尝试了几种不同的解决方案,如compare:
caseInsensitiveCompare:
等。
任何帮助在这里将不胜感激!
编辑+我知道这样的另一个问题被问到。给出的解决方案不是为字符串设计的,并且以升序返回数组,而不是因此而降序。 虽然我可以用这个工作,但我希望能够在这里学习如何使用字符串并仍然按照我期望的顺序获取数组。
用实际数字为你的钥匙,而不是字符串,它会工作得很好。 – rmaddy 2013-03-20 04:13:38
@maddy我意识到这可能会让事情变得更加简单,但是有时候玩家会有一个离开游戏板的位置,理想情况下这些位置不会被表示为数字,所以任何使用字符串将阻止我需要对我的程序的那部分进行更改。 – 2013-03-20 11:59:19