sorting with fetched results controller causes section titles to be wrong
I'm using a fetchedResultsController to get data for a table view.
Here is the code for the fetchedController:
NSEntityDescription *entity = [NSEntityDescription
entityForName:@"Appliance" inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:@开发者_运维知识库"name" ascending:NO];
[fetchRequest setSortDescriptors:[NSArray arrayWithObject:sort]];
[fetchRequest setFetchBatchSize:20];
NSFetchedResultsController *theFetchedResultsController =
[[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
managedObjectContext:context sectionNameKeyPath:@"productLine.name"
cacheName:@"Root"];
The section key path is using a related entity. Appliance <<--> ProductLine.
I'm getting the title for the sections in the table like this:
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
id <NSFetchedResultsSectionInfo> sectionInfo = [[fetchedResultsController sections] objectAtIndex:section];
return [sectionInfo name];
}
This works just fine, but if I change the sorting to "ascending:YES" then the table sections get the wrong titles.
I found the answer myself. It turns out that I need to sort the results by productLine.name and then sort them by name. So I added another sort descriptor.
NSSortDescriptor *aSort = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
NSSortDescriptor *pSort = [[NSSortDescriptor alloc] initWithKey:@"productLine.name" ascending:YES];
[fetchRequest setSortDescriptors:[NSArray arrayWithObjects:pSort, aSort, nil]];
All is well now.
精彩评论