2012-08-05 101 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:)]

相關問題