C中按字母顺序对数组控制器进行数字排序

C中按字母顺序对数组控制器进行数字排序

本文介绍了如何在Objective-C中按字母顺序对数组控制器进行数字排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个NSArrayController,我想对内容进行排序,以便首先对具有英文字母的内容进行排序,然后对具有数字和非英语字符的所有内容进行排序.

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.

例如:A,B,C ... Z,1、2、3 ... 9,구,결,...

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]];

推荐答案

您可以使用sortedArrayUsingComparator来根据需要自定义排序算法.例如,您可以使用以下几行来赋予符号优先级:

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];
}];

要将英语字符放在非英语字符之前,只需使用NSDiacriticInsensitiveSearch | NSCaseInsensitiveSearch作为选项,无需花哨的算法即可.

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

如果您需要无障碍地支持iOS,请尝试sortedArrayUsingSelector.

If you need to support iOS without blocks try sortedArrayUsingSelector.

这篇关于如何在Objective-C中按字母顺序对数组控制器进行数字排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 17:22