NSFetchedResultsController错误:索引X处的获取对象具有无序部分名称Y.对象必须按部分名称排序'

alh*_*hcr 3 sorting core-data uisearchbar ios4

我正在iPhone应用程序中实现搜索栏.我有Workers列表,每个都有属性:firstName,lastName,company.表视图的部分设置为company属性.

我在搜索时设置了谓词:

NSPredicate *predicate =[NSPredicate predicateWithFormat:@"firstName contains[cd] %@", searchBar.text];
Run Code Online (Sandbox Code Playgroud)

我得到错误:

NSFetchedResultsController ERROR: The fetched object at index 3 has an out of order section name 'company2. Objects must be sorted by section name'
Run Code Online (Sandbox Code Playgroud)

当我有sortDescriptor时:

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"lastName" ascending:YES selector:@selector(caseInsensitiveCompare:)]; 
Run Code Online (Sandbox Code Playgroud)

当我改变它时,我注意到了

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"firstName"` ascending:YES selector:@selector(caseInsensitiveCompare:)];
Run Code Online (Sandbox Code Playgroud)

现在搜索工作正常,没有错误.initWithKey参数是否必须与谓词中的属性名称匹配?我不明白.

Tec*_*Zen 15

来自NSFetchedResultsController文档:

获取请求必须至少有一个排序描述符.如果控制器生成节,则数组中的第一个排序描述符用于将对象分组为多个节; 其键必须与sectionNameKeyPath相同,或者使用其键的相对排序必须与使用sectionNameKeyPath的相匹配.

在您的情况下,您需要使用两种排序(在数组中.)元素1应该是公司名称属性的排序,第二个元素应该对lastName/firstName属性排序.