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]]]];
        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:等。

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

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

4

2 回答 2

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);
于 2013-03-20T04:15:50.540 回答
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);
于 2013-03-20T04:54:44.367 回答