使用特殊字符对数组进行排序 - iPhone

nco*_*hen 2 sorting iphone objective-c nsarray

我有一个带有法语字符串的数组,让我们说:"égrener"和"确切"我想对它进行排序,例如égrener是第一个.当我做:

NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObject:descriptor];
NSArray *sortedArray = [myArray sortedArrayUsingDescriptors:sortDescriptors];
Run Code Online (Sandbox Code Playgroud)

我在列表的末尾得到了é......我该怎么办?

谢谢

Nik*_*uhe 7

有一种方便的方法NSString可以让你轻松地进行这种类型的排序:

NSArray *sortedArray = [myArray sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
Run Code Online (Sandbox Code Playgroud)

NSString底层比较方法(compare:options:range:locale:)为您提供了更多如何进行排序的选项.

编辑:这是长篇故事:

首先,定义一个比较函数.这个适合自然字符串排序:

static NSInteger comparator(id a, id b, void* context)
{
    NSInteger options = NSCaseInsensitiveSearch
        | NSNumericSearch              // Numbers are compared using numeric value
        | NSDiacriticInsensitiveSearch // Ignores diacritics (â == á == a)
        | NSWidthInsensitiveSearch;    // Unicode special width is ignored

    return [(NSString*)a compare:b options:options];
}
Run Code Online (Sandbox Code Playgroud)

然后,对数组进行排序.

    NSArray* myArray = [NSArray arrayWithObjects:@"foo_002", @"fôõ_1", @"fôõ_3", @"?oo_0", @"?oo_1.5", nil];
    NSArray* sortedArray = [myArray sortedArrayUsingFunction:comparator context:NULL];
Run Code Online (Sandbox Code Playgroud)

示例中的数组包含一些有趣的字符:数字,变音符号和unicode范围ff00中的一些字符.最后一个字符类型看起来像ASCII字符,但以不同的宽度打印.

使用的比较函数以人类可预测的方式处理所有情况.排序的数组具有以下顺序:

?oo_0
fôõ_1
?oo_1.5
foo_002
fôõ_3
Run Code Online (Sandbox Code Playgroud)