NSFetchedResultsController按名字或姓氏排序 [英] NSFetchedResultsController sort by first name or last name

查看:88
本文介绍了NSFetchedResultsController按名字或姓氏排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我基本上是在尝试实现

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.

目前我有

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

推荐答案

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

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

然后只有一个使用键sortKey

这篇关于NSFetchedResultsController按名字或姓氏排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆