iOS: Sorting and grouping NSFetchedResultsController

喜欢而已 提交于 2019-12-08 07:56:38

问题


I have two tables with the following structure

MainCategory:

name position hasSubCategories

SubCategory:

name position display belongsToMainCategory

Now I want to display all subcategories (where display attribute = YES) grouped by main category. The main category sections should be sorted as defined by position and the subcategories itself (within the section) by their position attribute. (name by the way can be the same for a certain main category...my tables have more attributes but they aren't relevant to understand the problem). But my order is completely messed up. Why? Here's my code for the 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];

回答1:


The key path used as sectionNameKeyPath: argument to the fetched results controller must be the same key that is used in the first sort descriptor or generate the same relative ordering.

The fetched results controller first orders all fetched objects according to the first sort descriptor and then groups the objects into sections according to the sectionNameKeyPath. Therefore using different key paths (as in your case "belongsToMainCategory.position" vs. "belongsToMainCategory.name") does not work. This could even cause a runtime error about "out of order sections".



来源:https://stackoverflow.com/questions/20812564/ios-sorting-and-grouping-nsfetchedresultscontroller

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