iOS:对NSFetchedResultsController进行sorting和分组

我有两个表结构如下

MainCategory:

name position hasSubCategories 

子类别:

 name position display belongsToMainCategory 

现在我想要显示按主类别分组的所有子类别(其中显示属性= YES)。 主类别部分应按照位置和子类别(在部分内)通过其位置属性进行sorting。 (名称的方式可以是一样的主要类别…我的表具有更多的属性,但他们是不相关的了解问题)。 但我的订单完全搞砸了。 为什么? 这是我的FetchedResultsController的代码:

  NSError *error = nil; NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"SubCategory"]; NSSortDescriptor *mainCatPosition = [[NSSortDescriptor alloc] initWithKey:@"belongsToMainCategory.position" ascending:YES]; NSSortDescriptor *subCatPosition = [[NSSortDescriptor alloc] initWithKey:@"position" ascending:YES]; request.sortDescriptors = [NSArray arrayWithObjects:mainCatPosition,subCatPosition,nil]; request.predicate = [NSPredicate predicateWithFormat:@"display = %@", [NSNumber numberWithBool:YES]]; [self.db.managedObjectContext executeFetchRequest:request error:&error]; self.fetchedResultsController = [[NSFetchedResultsController alloc]initWithFetchRequest:request managedObjectContext:self.budgetDatabase.managedObjectContext sectionNameKeyPath:@"belongsToMainCategory.name" cacheName:nil]; 

用作获取结果控制器的sectionNameKeyPath:参数的键path必须与第一个sorting描述符中使用的键相同, 或者生成相同的相对sorting。

获取的结果控制器首先根据第一个sorting描述符对所有获取的对象进行sorting,然后根据sectionNameKeyPath将这些对象分成多个部分。 因此,使用不同的关键path(如在你的情况“belongsToMainCategory.position”与“belongsToMainCategory.name”)不起作用。 这甚至可能会导致“无序部分”的运行时错误。