按升序排序nsarray

Sam*_*m B 2 iphone xcode ipad ios

我有一个NSdictonary对象具有以下键值

keys: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
Run Code Online (Sandbox Code Playgroud)

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

有什么建议?

Joa*_*son 11

您应该能够使用sortedArrayUsingComparatorwith options:NSNumericSearch来对其进行排序,以便按照实际的数字顺序进行排序,因为10在严格按字母顺序排序的2之前出现;

NSArray * sortedKeys = 
    [myKeys sortedArrayUsingComparator:^(id string1, id string2) {
        return [((NSString *)string1) compare:((NSString *)string2) 
                                      options:NSNumericSearch];
}];
Run Code Online (Sandbox Code Playgroud)