简体   繁体   中英

Sorting an NSArray

I have an NSArray as follows:

NSArray *directoryContent = [[NSFileManager defaultManager] directoryContentsAtPath:filePath];

The files at filePath are:

11.thm, 12.thm, 13.thm,...,Text_21.thm, Text_22.thm, Text_23.thm,...

I would like to sort the NSArray in the order:

13.thm, 12.thm, 11.thm,..., Text_23.thm, Text_22.thm, Text_21.thm,...

How do I achieve this?

Write a custom sorting function:

NSInteger customSortingFunctionReversedAndNumericFirst(NSString *string1, NSString *string2, void *context) {
    NSCharacterSet *decimalCharacterSet;
    BOOL firstStringStartsWithNumeric,
        secondStringStartsWithNumeric;


    decimalCharacterSet = [NSCharacterSet decimalDigitCharacterSet];
    firstStringStartsWithNumeric = [decimalCharacterSet characterIsMember:[string1 characterAtIndex:0]];
    secondStringStartsWithNumeric = [decimalCharacterSet characterIsMember:[string2 characterAtIndex:0]];



    if (firstStringStartsWithNumeric != secondStringStartsWithNumeric) {
        return firstStringStartsWithNumeric ? NSOrderedAscending : NSOrderedDescending;
    }

    return [string2 compare:string1 options:NSNumericSearch];
}

and use it like this:

NSArray *sortedDirectoryContent = [directoryContent sortedArrayUsingFunction:customSortingFunctionReversedAndNumericFirst context:NULL]

I have made many assumption, but this code works on your sample array and similar input values.
The main assumption is that you wanted this particular order only for strings that start with a numeric value. If it's not the case, you can use this code to adapt it to the algorithm you want.

I think that the simpliest solution is to use sortedArrayUsingSelector: with caseInsensitiveCompare: (from NSString) :

NSArray *sortedDirectoryContent =
[directoryContent sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];

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