简体   繁体   中英

sorting nsarray in ascending order

I have an NSdictonary object with following key values

keys: 1.infoKey, 2.infoKey, 3.infoKey, 4.infoKey, 5.infoKey, 6.infoKey, 7.infoKey, 8.infoKey, 9.infoKey, 10.infoKey, 11.infoKey

Note they are not sorted and can be in any order ie 3.infoKey, 7.infoKey, 2.infoKey etc

What I am trying to do is sort the key values out ie 1,2,3,4,5,6,7,8,9,10,11 .... This is the code I have used so far but every time I do a sort, it sorts it in order that I don't want (see below)

    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

I tried both ways and they both give the same results. I searched every where on stack overflow and google but couldn't find a fit for my needs.

Any suggestions?

You should be able to sort it using sortedArrayUsingComparator with options:NSNumericSearch to get it in real numeric order, since 10 comes before 2 in a strictly alphabetical sort;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM