我使用排序描述符对获取请求的结果进行排序。
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、G、V、Y、Z。
所以这封信在第12位。
我不知道为什么,但是在获取对象之后使用比较器是有效的。因此,它适用于任何数组,但不适用于fetch请求的排序描述符。
发布于 2012-08-05 19:00:17
看看我在NSFetchedResultsController v.s. UILocalizedIndexedCollation的问题的细节,我展示了如何使用UILocalizedIndexedCollation正确地生成字母表,并使用基于UILocalizedIndexCollation的正确排序方法进行排序。我的问题只是询问一个更好的方法来做这件事。
如果您不使用UILocalizedIndexCollation,您应该只使用localizedStandardCompare:而不是localizedStandardCompare视频中提到的localizedCompare进行本地化。
发布于 2012-08-04 23:10:37
试一试
[NSSortDescriptor alloc] initWithKey:@"property" ascending:YES selector:@selector(localizedCompare:)]
编辑
@Mert更新了他的问题。现在看来,localizedCompare:
对土耳其字母进行了正确的排序,但是不能处理fetch请求。
下面是我为测试这个问题所做的工作。也许您可以检查这在您的环境中是否有效,然后在那里工作:
// 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”。
发布于 2013-04-30 03:53:21
我也有类似的问题:
[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:)]
https://stackoverflow.com/questions/11814560
复制