2012-08-05 161 views
5

我使用排序描述符对提取请求的结果进行排序。如何使用nspredicate对非英文字符串进行排序?

NSFetchRequest* req = [[NSFetchRequest alloc] initWithEntityName:[MyEntity entityName]]; 
NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"property" 
                  ascending:YES 
                  selector:@selector(localizedCompare:)]; 
req.sortDescriptors = [NSArray arrayWithObject:descriptor]; 
return [self.managedObjectContext executeFetchRequest:req error:nil]; 

问题是单词以非英语字符开头,如'İ'列在列表末尾。这是一个土耳其字母,字母看起来像这样:

A,B,C,Ç,D,E,F,G,H,H,I,J,K,L,M, N,O,Ö,P,R,S,Ş,T,U,Ü,V,Y,Z.

所以这封信是在第12位。

我不知道为什么,但在获取对象后使用比较器工作。所以它适用于任何数组,但不适用于获取请求的排序描述符。

回答

3

查看我的问题的详细信息,在NSFetchedResultsController v.s. UILocalizedIndexedCollation我演示了如何使用UILocalizedIndexedCollat​​ion正确生成字母表并使用基于UILocalizedIndexCollat​​ion的正确排序方法进行排序。我的问题只是围绕要求更好的方式来做到这一点。

如果您不使用UILocalizedIndexCollat​​ion,则应该只使用localizedStandardCompare:not localizedCompare,如WWDC视频中提到的本地化。

1

尝试

[NSSortDescriptor alloc] initWithKey:@"property" ascending:YES selector:@selector(localizedCompare:)] 

编辑

@Mert已经更新了他的问题。现在看来,localizedCompare:正确地对土耳其字母进行排序,但对于获取请求无效。

这是我所做的测试这个问题。也许你可以检查是否在您的环境中工作,然后从那里开始工作:

// Create some entities: 
NSArray *a = @[@"İ", @"J", @"Ğ", @"G", @"H", @"I", @"Ç", @"C"]; 
for (NSString *s in a) { 
    MyEntity *e = [NSEntityDescription insertNewObjectForEntityForName:@"MyEntity" 
               inManagedObjectContext:self.managedObjectContext]; 
    e.name = s; 
} 

// Fetch all entities in sorted order: 
NSFetchRequest* req = [[NSFetchRequest alloc] initWithEntityName:@"MyEntity"]; 
NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"name" 
                  ascending:YES 
                  selector:@selector(localizedCompare:)]; 
req.sortDescriptors = [NSArray arrayWithObject:descriptor]; 
NSArray *result = [self.managedObjectContext executeFetchRequest:req error:nil]; 

“myEntity所”是一个“name”属性String类型的核心数据实体。

+0

它,它是基于用户的语言

尝试在NSString创建一个类别,内容如下创造一个干净NSLocale为此需要没有工作。我也尝试改变模拟器的语言。 – Mert 2012-08-05 07:28:34

+0

这很奇怪。如果我用'[myArray sortedArrayUsingSelector:@selector(localizedCompare :)]对数组排序',那么我会得到正确的结果。你能告诉代码你如何设置获取请求吗? – 2012-08-05 08:19:01

+0

我编辑了我的问题并添加了代码 – Mert 2012-08-05 09:19:52

0

我有一个类似的问题:

[strArr sortedArrayUsingSelector:@selector(localizedCompare:)]

似乎

localizedCompare

电话

compare:other options:nil range:NSMakeRange(0, self.length) locale: [NSLocale currentLocale]];

根据用户偏好,可能处于混合状态。

-(NSComparisonResult)currentLocalCompare:(id)other 
{ 
    NSLocale * currLoc = [NSLocale currentLocale]; //get current locale 
    NSLocale * loc = [[NSLocale alloc] initWithLocaleIdentifier:currLoc.localeIdentifier];//lets create a new clean NSLocale based on users prefared langauge 
    return [self compare:other options:nil range:NSMakeRange(0, self.length) locale:loc];//compare using clean NSLocale 
} 

,并调用它像:

[strArr sortedArrayUsingSelector:@selector(currentLocalCompare:)]

相关问题