Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort array controller alphabetically with numbers last in objective-c?

I have an NSArrayController and I would like to sort the contents so that anything with English alphabets are sorted first and then anything with numbers and non English characters are sorted last.

For example: A, B , C ... Z, 1 , 2, 3 ... 9, 구, 결, ...

Currently I only know how to sort items in alphabetical order. Suggestions?

NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
        [dataController setSortDescriptors: [NSArray arrayWithObject: sort]];
like image 313
David Avatar asked Dec 02 '22 00:12

David


1 Answers

You can use sortedArrayUsingComparator to customize the sort algorithm to your needs. For instance, you can give precedence to symbols with this lines:

NSArray *assorted = [@"1 2 3 9 ; : 구 , 결 A B C Z ! á" componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSArray *sorted = [assorted sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
    /* NSOrderedAscending, NSOrderedSame, NSOrderedDescending */
    BOOL isPunct1 = [[NSCharacterSet punctuationCharacterSet] characterIsMember:[(NSString*)obj1 characterAtIndex:0]];
    BOOL isPunct2 = [[NSCharacterSet punctuationCharacterSet] characterIsMember:[(NSString*)obj2 characterAtIndex:0]];
    if (isPunct1 && !isPunct2) {
        return NSOrderedAscending;
    } else if (!isPunct1 && isPunct2) {
        return NSOrderedDescending;
    }
    return [(NSString*)obj1 compare:obj2 options:NSDiacriticInsensitiveSearch|NSCaseInsensitiveSearch];         
}];

To put English characters before non-English ones, it'd be enough to use NSDiacriticInsensitiveSearch | NSCaseInsensitiveSearch as options, no fancy algorithm required.

If you need to support iOS without blocks try sortedArrayUsingSelector.

like image 175
djromero Avatar answered Dec 19 '22 12:12

djromero