I have a list of alphanumeric names and when I run the code below the digits are ordered before the A-Z (0-9 A-Z).
How can I make this NSSortDescriptor put the digit at the end of the array (A-Z 0-9)?
NSSortDescriptor *sortNameSortDescriptor =
[NSSortDescriptor sortDescriptorWithKey:@"sortName"
ascending:YES
selector:@selector(localizedStandardCompare:)];
NSArray *sortedArray = [sortSectionsArray sortedArrayUsingDescriptors:@[ sortNameSortDescriptor ]];
Perhaps you could use an NSComparator based sort descriptor?
Rough Outline
NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:@"sortName" ascending:YES
comparator:^NSComparisonResult(NSString* obj1, NSString* obj2)
{
//Return negative number, zero or positive based on
//first letter being number or alpha.
//If obj1 starts with a letter and obj2 starts with a number then
//return NSOrderedAscending. . . otherwise just return [obj1 comppare:obj2];
//To test if first chararacter is a letter:
NSRange first = [obj1 rangeOfComposedCharacterSequenceAtIndex:0];
NSRange match = [obj1 rangeOfCharacterFromSet:[NSCharacterSet letterCharacterSet] options:0 range:first];
if (match.location != NSNotFound) {//Implement above comment}
}];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With