2

我有一个具有以下键值的 NSditonary 对象

密钥:1.infoKey、2.infoKey、3.infoKey、4.infoKey、5.infoKey、6.infoKey、7.infoKey、8.infoKey、9.infoKey、10.infoKey、11.infoKey

请注意,它们没有排序,可以按任何顺序排列,即 3.infoKey、7.infoKey、2.infoKey 等

我要做的是对键值进行排序,即 1,2,3,4,5,6,7,8,9,10,11 .... 这是我迄今为止使用的代码,但每次我做了一个排序,它按我不想要的顺序排序(见下文)

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *stringsPlistPath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"talkBtns.plist"];

        NSMutableDictionary *dictionary2 = [[NSMutableDictionary alloc] initWithContentsOfFile:stringsPlistPath];


        NSArray *myKeys = [dictionary2 allKeys];

//This didn't give the right results
        //sortedKeys = [myKeys sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];

//This didn't give the right results either
        NSSortDescriptor* sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:nil ascending:YES selector:@selector(localizedCompare:)];
        sortedKeys = [myKeys sortedArrayUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];

    // ***********
        // GET KEY VALUES TO
        // LOOP OVER
        // ***********
        /* */
        for (int i = 0; i < [sortedKeys count]; i++) 
        {
            NSLog(@"[sortedKeys objectAtIndex:i]: %@", [sortedKeys objectAtIndex:i]);
        }

    //output I get
    [sortedKeys objectAtIndex:i]: 1.infoKey
    [sortedKeys objectAtIndex:i]: 10.infoKey
    [sortedKeys objectAtIndex:i]: 11.infoKey
    [sortedKeys objectAtIndex:i]: 2.infoKey
    [sortedKeys objectAtIndex:i]: 3.infoKey
    [sortedKeys objectAtIndex:i]: 4.infoKey
    [sortedKeys objectAtIndex:i]: 5.infoKey
    [sortedKeys objectAtIndex:i]: 6.infoKey
    [sortedKeys objectAtIndex:i]: 7.infoKey
    [sortedKeys objectAtIndex:i]: 8.infoKey
    [sortedKeys objectAtIndex:i]: 9.infoKey

我尝试了两种方法,它们都给出了相同的结果。我搜索了堆栈溢出和谷歌的每个地方,但找不到适合我的需求。

有什么建议么?

4

1 回答 1

11

您应该能够使用sortedArrayUsingComparatorwithoptions:NSNumericSearch对其进行排序以按实际数字顺序获取它,因为在严格的字母排序中,10 在 2 之前;

NSArray * sortedKeys = 
    [myKeys sortedArrayUsingComparator:^(id string1, id string2) {
        return [((NSString *)string1) compare:((NSString *)string2) 
                                      options:NSNumericSearch];
}];
于 2012-09-30T15:29:54.810 回答