views:

308

answers:

2
+1  Q: 

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?

+2  A: 

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

NSArray *sortedDirectoryContent =
[directoryContent sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];
greg
Your code will not sort the array as requested. It will return the files in the order: 11.thm, 12.thm, 13.thm,...,Text_21.thm, Text_22.thm, Text_23.thm,...
pheelicks
To achieve the sort order he wants, he might need a different selector, because he wants numerically descending sorting, but with text lower than numbers.
MrMage
Thanks anyway Greg. That's true pheelicks n Mr. M.
erastusnjuki
+5  A: 

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.

Guillaume
Good Solution +1.
erastusnjuki