sam*_*tte 5 sorting iphone core-data tableview
我有一堆艺术家存储在CoreData中,并希望按名称对它们进行排序,但忽略前缀"the".因此,例如"甲壳虫乐队"将被归类为"甲壳虫乐队",有点像iTunes/iPod所做的那样.
所以我尝试cleanName在Artist模型中添加一个自定义属性,以便它可以用于排序:
NSSortDescriptor *sortByName = [[NSSortDescriptor alloc] initWithKey:@"cleanName" ascending:YES];
Run Code Online (Sandbox Code Playgroud)
这显然会降低应用程序,因为cleanName它不是SQLEntity的属性:
...keypath cleanName not found in entity <NSSQLEntity Artist id=1>
Run Code Online (Sandbox Code Playgroud)
我知道我可以在商店中保存cleanName,但这对我来说似乎不对.一个新的属性只是将名称剥离了"the"前缀?真?
所以相反,我尝试使用自定义compareObject:toObject:implementation来子类化NSSortDescriptor:
- (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];
}
Run Code Online (Sandbox Code Playgroud)
当我添加一位新艺术家,将"披头士乐队"添加到我的商店时,这就有效.艺术家被分类为"披头士乐队"并显示在我的"B"部分内.但是一旦我退出应用程序并重新启动它,我就会收到以下错误,并且tableview只保持空白:
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'
Run Code Online (Sandbox Code Playgroud)
你可以从我正在记录的内容中看到,章节标题很好(披头士的章节标题是B,因为它应该是).但是排序被打破了,因为这个记录应该在"倭黑猩猩"之前.
知道怎么解决这个问题吗?