2010-03-22 62 views
2

我有一个法语字符串数组让我说:“égrener”和“确切”我想排序它,如égrener是第一个。当我这样做:用特殊字符对数组进行排序 - iPhone

NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES]; 
NSArray *sortDescriptors = [NSArray arrayWithObject:descriptor]; 
NSArray *sortedArray = [myArray sortedArrayUsingDescriptors:sortDescriptors]; 

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

感谢

回答

5

有一个在NSString一个方便的方法,可以让你做这类容易排序:

NSArray *sortedArray = [myArray sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)]; 

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

然后,排序数组。

NSArray* myArray = [NSArray arrayWithObjects:@"foo_002", @"fôõ_1", @"fôõ_3", @"foo_0", @"foo_1.5", nil]; 
    NSArray* sortedArray = [myArray sortedArrayUsingFunction:comparator context:NULL]; 

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

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

foo_0 
fôõ_1 
foo_1.5 
foo_002 
fôõ_3 
+0

感谢,但我真的不明白我怎么可以实现和名称排序呢? – ncohen 2010-03-22 13:55:48

+0

关键是区域设置参数。您现在的问题是系统语言环境设置为英语。你需要它设置为法语。您可以在系统或应用程序级别为法语应用程序执行此操作。如果您只是偶尔需要处理法语,则可以将适当的语言环境传递给排序,以便现在使用法语而不是英语排序。阅读Apple Docs中的本地化内容。这听起来像你会使用它很多。 – TechZen 2010-03-22 14:35:25

+0

不明白它......它不是一个本地化的问题......它是一个数组中特殊字符的问题! – ncohen 2010-03-22 14:36:58