NSFetchedResultsController按名字或姓氏排序
我基本上是试图用名字和姓氏,或用名字或姓氏来实现NSSortDescriptor? 但是有一个NSFetchedResultsController。 我正在阅读地址簿中的记录,并希望像地址簿一样显示它们。
记录将根据姓氏的第一个字母进行分类。 如果没有姓,它将按名排序,如果没有名字,则按公司排序。
目前我有
- (NSFetchedResultsController *)fetchedResultsController {
if (_fetchedResultsController != nil) {
return _fetchedResultsController;
}
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
// read the contact list
NSEntityDescription *entity = [Contact MR_entityDescriptionInContext:[NSManagedObjectContext MR_defaultContext]];
[fetchRequest setEntity:entity];
// sort the results by last name then by first name
NSSortDescriptor *sort1 = [[NSSortDescriptor alloc] initWithKey:@"lastName" ascending:YES selector:@selector(caseInsensitiveCompare:)];
NSSortDescriptor *sort2 = [[NSSortDescriptor alloc] initWithKey:@"firstName" ascending:YES selector:@selector(caseInsensitiveCompare:)];
[fetchRequest setSortDescriptors:@[sort1, sort2]];
// Fetch all the contacts and group them by the firstLetter in the last name. We defined this method in the CoreData/Human/Contact.h file
NSFetchedResultsController *theFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:[NSManagedObjectContext MR_defaultContext] sectionNameKeyPath:@"firstLetter" cacheName:nil];
self.fetchedResultsController = theFetchedResultsController;
_fetchedResultsController.delegate = self;
return _fetchedResultsController;
}
按姓氏和名字排序。 我将如何改变这个返回上面列出的想要的结果?
您可以在Contact
上创建具有该逻辑的实例方法:
- (NSString *)sortKey
{
if(self.lastName) {
return [self.lastName substringToIndex:1];
}
if(self.firstName) {
return [self.firstName substringToIndex:1];
}
return [self.companyName substringToIndex:1];
}
这时正好有一个NSSortDescriptor
使用的关键sortKey
上一篇: NSFetchedResultsController sort by first name or last name
下一篇: NSFetchedResultsController and NSPredicate and a section name