NSFetchedResultsController sort by first name or last name

风格不统一 提交于 2019-12-11 10:03:27

问题


I am basically trying to achieve NSSortDescriptor with first name and last name,or with either first name or last name? but with an NSFetchedResultsController. I am reading records from the address book and want to display them just like the Address Book does.

The records will be sorted into sections based on first letter of last name. If there isn't a last name it will sort by first name and if there isn't a first name it will sort by company.

Currently I have

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

}

Which sorts by last name and then first name. How would I alter this to return the wanted results listed above?


回答1:


You can just create an instance method on Contact that has that logic:

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

    if(self.firstName) {
        return [self.firstName substringToIndex:1];
    }

    return [self.companyName substringToIndex:1];
}

Then just have one NSSortDescriptor that uses the key sortKey



来源:https://stackoverflow.com/questions/25294513/nsfetchedresultscontroller-sort-by-first-name-or-last-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!