2013-03-20 86 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