MichiZH
MichiZH

Reputation: 5817

iOS: Sorting and grouping NSFetchedResultsController

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

Upvotes: 1

Views: 510

Answers (1)

Martin R
Martin R

Reputation: 540105

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".

Upvotes: 6

Related Questions