title: iOS: Sorting and grouping NSFetchedResultsController
body: <p>I have two tables with the following structure</p>
  
  <p>MainCategory:</p>
  
  <pre><code>name position hasSubCategories
  </code></pre>
  
  <p>SubCategory:</p>
  
  <pre><code>name position display belongsToMainCategory
  </code></pre>
  
  <p>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:</p>
  
  <pre><code>    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:&amp;error];
  
      self.fetchedResultsController = [[NSFetchedResultsController alloc]initWithFetchRequest:request
                                                                         managedObjectContext:self.budgetDatabase.managedObjectContext
                                                                           sectionNameKeyPath:@"belongsToMainCategory.name"
                                                                                    cacheName:nil];
  </code></pre>