Creating table sections with NSFetchedResultsController

core-data, ios, nsfetchedresultscontroller, objective-c, uitableview

Solution

It's simple! Just provide the NSFetchedResultsController with a `sectionNameKeyPath` (which in this case would be `hasDog`) in its initializer.

The one caveat to this, however, is the section names will be `0` & `1` respectively, but it's easily curable.

Problem

I'm using `NSFetchedResultsController` to drive the data for my `UITableViewController`. A simplified version of the managed object I am fetching looks like this (well for example): ``` Person: -(BOOL)hasPet; -(BOOL)hasDog; ``` Basically, I want my table to only show those `Person` objects who have a pet. So that's simple, I can use a predicate. Now, for those who `hasPet == YES`, I want to put them in the table in 2 sections, first section `hasDog == YES`, and the second is `hasDog == NO`. This is where I'm a little fuzzy. Here is where I configure my results controller, hopefully someone can help steer me in the right direction. ``` - (NSFetchedResultsController *)fetchedResultsController { if (nil != fetchedResultsController) { return fetchedResultsController; } NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"Homework" inManagedObjectContext:managedObjectContext]; [fetchRequest setEntity:entity]; NSPredicate *predicate = [NSPredicate predicateWithFormat:@"hasPet == %@", [NSNumber numberWithBool:YES]]; [fetchRequest setPredicate:predicate]; NSSortDescriptor *dogDescriptor = [[NSSortDescriptor alloc] initWithKey:@"hasDog" ascending:YES]; NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES]; NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:dogDescriptor, sortDescriptor, nil]; [fetchRequest setSortDescriptors:sortDescriptors]; NSFetchedResultsController *aController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:managedObjectContext sectionNameKeyPath:nil cacheName:nil]; aController.delegate = self; self.fetchedResultsController = aController; // Release things return fetchedResultsController; } ``` Is a sort descriptor where I need to be focusing my attention?

Original source