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 に答える