我有一堆存儲在CoreData中的藝術家,並希望按名稱排序它們,但忽略前綴「the」。因此,例如「披頭士樂隊」將被歸類爲「披頭士」,就像iTunes/iPod所做的一樣。NSSortDescriptor刪除「該」前綴
所以我嘗試添加自定義cleanName
屬性來我的藝術家模型,因此可以用於與排序:
NSSortDescriptor *sortByName = [[NSSortDescriptor alloc] initWithKey:@"cleanName" ascending:YES];
這顯然帶來下來的應用程序爲cleanName
不是SQLEntity的屬性:
...keypath cleanName not found in entity <NSSQLEntity Artist id=1>
我知道我可以將cleanName保存在商店中,但它對我來說似乎是錯誤的。一個新的屬性,只是名稱被剝奪了「the」前綴?真?
所以不是,我試圖用一個自定義的compareObject繼承NSSortDescriptor:toObject:實現:
- (NSComparisonResult)compareObject:(Artist*)artist1 toObject:(Artist*)artist2 {
NSString *cleanString1 = [artist1.name stringByReplacingOccurrencesOfString:@"the " withString:@"" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [artist1.name length])];
NSString *cleanString2 = [artist2.name stringByReplacingOccurrencesOfString:@"the " withString:@"" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [artist2.name length])];
return [artist1.cleanName compare:artist2.cleanName options:NSCaseInsensitiveSearch];
}
當我添加一個新的藝術家這工作,說:「披頭士」我的店鋪。藝術家被排序爲「披頭士」,並顯示在我的「B」部分。但只要我退出應用程序並重新啓動它,我收到以下錯誤,並且實現代碼如下只是停留空:
sectionIndex A for Apparat
sectionIndex B for Bonobo
sectionIndex M for Misteur Valaire
sectionIndex M for Moderat
sectionIndex P for Paul Kalkbrenner
sectionIndex R for Röyksopp
sectionIndex B for The Beatles
NSFetchedResultsController ERROR: The fetched object at index 6 has an out of order section name 'R. Objects must be sorted by section name'
正如你從什麼,我記錄看,該部分的標題都很好(披頭士'部分標題是B,因爲它應該是)。但排序被打破,因爲這個記錄應該在「倭黑猩猩」之前。
任何想法如何解決這個問題?
你是如何實現* cleanName *的?這似乎是一個短暫的財產,該實體將是一條路。 – Huperniketes 2011-07-02 16:55:40
我很確定瞬態屬性不能用於NSFetchedResultsControllers中的排序。 – samvermette 2011-07-05 04:39:37