NSArray不按数字顺序排序

时间:2013-03-20 04:03:27

标签: ios nsmutablearray nsarray nsdictionary

我希望用字典中的项目创建一个数组,然后按降序排序,以便最大值位于顶部,最小值位于底部。但是,当我的项目长度超过一位时似乎很难。

我的代码是这样的:

// 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:等。

非常感谢任何帮助!

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

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分: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);