NSFetchedResultsController按名字或姓氏排序

时间:2014-08-13 19:26:20

标签: ios objective-c sorting nsfetchedresultscontroller

我基本上尝试使用NSFetchedResultsController来实现NSSortDescriptor with first name and last name,or with either first name or last name?。我正在阅读地址簿中的记录,并希望像地址簿一样显示它们。

记录将根据姓氏的第一个字母分类。如果没有姓氏,它将按名字排序,如果没有名字,它将按公司排序。

目前我有

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

}

按姓氏和名字排序。我如何改变这个以返回上面列出的通缉结果?

1 个答案:

答案 0 :(得分:0)

您可以在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