NSFetchedResultsController按名字或姓氏sorting

我基本上是试图用名字和姓氏,或者名字或姓氏来实现NSSortDescriptor? 但是有一个NSFetchedResultsController。 我正在阅读地址簿中的logging,并希望像地址簿一样显示它们。

logging将根据姓氏的第一个字母分类。 如果没有姓,则按名字sorting,如果没有名字,则按公司sorting。

目前我有

- (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; } 

按姓氏和名字sorting 我将如何改变这个返回上面列出的想要的结果?

你可以在Contact上创build一个具有该逻辑的实例方法:

 - (NSString *)sortKey { if(self.lastName) { return [self.lastName substringToIndex:1]; } if(self.firstName) { return [self.firstName substringToIndex:1]; } return [self.companyName substringToIndex:1]; } 

然后,只需要一个使用密钥sortKey