I am currently working on an application that has a couple of entities and relationships, as shown below:
Element β Category .
I am currently retrieving instances of Item and displaying them in sections using the category.name element. In this case, I can use the sort descriptor to sort the categories by name, which is quite simple and works fine (corresponding code below):
-(NSFetchedResultsController*)fetchedResultsController { if (fetchedResultsController_ != nil) return fetchedResultsController_; NSManagedObjectContext *moc = [order_ managedObjectContext]; NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"Item" inManagedObjectContext:moc]; [fetchRequest setEntity:entity]; NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"category.name" ascending:YES]; NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil]; [fetchRequest setSortDescriptors:sortDescriptors]; [sortDescriptors release]; [sortDescriptor release]; NSFetchedResultsController *controller = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:moc sectionNameKeyPath:@"category.name" cacheName:nil]; controller.delegate = self; self.fetchedResultsController = controller; [controller release]; [fetchRequest release]; NSError *error = nil; if (![fetchedResultsController_ performFetch:&error]) {
Now my problem is that I need to sort these categories not by name, but by using the (NSNumber*) displayOrder , which is part of the Category object. BUT I need section headings in the table to continue using the name category.
If I set sortDescriptor to use category.displayOrder and save sectionNameKeyPath as category.name , the section headers work fine, but the sortDescriptor is simply ignored by the fetchedResultsController and the table sections are sorted by category name (not sure why ??).
My next idea was to overwrite the displayOrder getter method, but that didn't get me too far, since the return types are different from each other, plus I needed the actual displayOrder value to sort the section.
So right now, I have a solution that seems a bit awkward (the code below), and I'm wondering if there is a better way to achieve the same thing using only fetchedResultsController.
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
Did I miss something basic here?
Thanks in advance for your thoughts.
Horn