如何使用nspredicate对非英语字符串进行排序?

时间:2012-08-05 07:01:21

标签: objective-c ios cocoa-touch core-data nssortdescriptor

我正在使用排序描述符对获取请求的结果进行排序。

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,I,İ,J,K,L,M,N,O,Ö,P,R,S,Ş,T ,U,Ü,V,Y,Z。

所以这封信是第12位。

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

3 个答案:

答案 0 :(得分:3)

NSFetchedResultsController v.s. UILocalizedIndexedCollation查看我的问题的详细信息。我将展示如何使用UILocalizedIndexedCollat​​ion正确生成Alphabet并使用基于UILocalizedIndexCollat​​ion的正确排序方法进行排序。我的问题围绕着要求更好的方法来做到这一点。

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

答案 1 :(得分: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”是一个Core Data实体,其中一个属性为“String”,类型为String。

答案 2 :(得分:0)

我遇到了类似的问题:

[strArr sortedArrayUsingSelector:@selector(localizedCompare:)]

似乎

localizedCompare

来电

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

[NSLocale currentLocale]可能处于混合状态,具体取决于用户首选项。因此需要根据用户语言

创建一个干净的NSLocale

尝试使用以下内容在NSString上创建类别:

-(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:)]