2013-03-20 84 views
0

我正在寻找一个字典中的项目数组,然后按降序排列,以便最大值位于顶部,最小值位于底部。然而,当我的物品长度超过一位时,它似乎很难。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:等。

任何帮助在这里将不胜感激!

编辑+我知道这样的另一个问题被问到。给出的解决方案不是为字符串设计的,并且以升序返回数组,而不是因此而降序。 虽然我可以用这个工作,但我希望能够在这里学习如何使用字符串并仍然按照我期望的顺序获取数组。

+0

用实际数字为你的钥匙,而不是字符串,它会工作得很好。 – rmaddy 2013-03-20 04:13:38

+0

@maddy我意识到这可能会让事情变得更加简单,但是有时候玩家会有一个离开游戏板的位置,理想情况下这些位置不会被表示为数字,所以任何使用字符串将阻止我需要对我的程序的那部分进行更改。 – 2013-03-20 11:59:19

回答

1

试试这个:

NSArray *array = @[@"1",@"31",@"14",@"531",@"4",@"53",@"64",@"4",@"0"]; 

NSArray *sortedArray = [array sortedArrayUsingComparator:^(id str1, id str2) { 
     return [((NSString *)str1) compare:((NSString *)str2) options:NSNumericSearch]; 
    }]; 
NSLog(@"%@",sortedArray); 
0

试试这个,

// 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]]]]; 
    } 
NSArray *arrKeys = [[newDictionary allKeys]; 
NSArray *sortedArray = [arrKeys sortedArrayUsingComparator:^(id firstObject, id secondObject) { 
    return [((NSString *)firstObject) compare:((NSString *)secondObject) options:NSNumericSearch]; 
}]; 
NSLog(@"%@",sortedArray); 
+0

我刚刚试过这个,日志输出是1,11,2,6 你能想到它不工作的原因吗? – 2013-03-20 16:52:28

+0

@AlanTaylor我已经发布更新的代码,现在检查它 – Ravindhiran 2013-03-21 05:26:28

+0

非常感谢Ravindhiran,我会尝试这个,当我今晚回家! – 2013-03-21 16:53:00