NSFetchedResultsController sort by first name or last name

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?


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

链接地址: http://www.djcxy.com/p/36168.html

上一篇: NSSortDescriptor应该对NSDates进行排序

下一篇: NSFetchedResultsController按名字或姓氏排序