NSFetchedResultController section by relationship?

| | August 6, 2015

I have a tableview with a NSFetchedResultController as the datasource. I have two entities like this



I want to have the tableview to display all the data from Book entity grouped by Library relationship. At the moment, there is only 1 library so there are only 2 sections. Books that has book.library == nil will appear on top in section 0, and books that has a library will appear in the second section.

I tried this but didn’t work

NSFetchRequest *request = [[NSFetchRequest alloc]initWithEntityName:@"Books"];
request.sortDescriptors = @[[[NSSortDescriptor alloc]initWithKey:@"library" ascending:YES]];
NSFetchedResultsController *returnFetchRC = [[NSFetchedResultsController alloc]initWithFetchRequest:request managedObjectContext:self.managedObjectContext sectionNameKeyPath:@"library" cacheName:nil];

How do I do that? Thanks


It did not work because some library is nil in some book objects. I had to add a isInLibrary attribute flag to book entity and set default value to NO then sort and set sectionNameKeyPath to the new attribute to make it work. That solution is not pretty. Is there anyway to make FRC to group by relationship that could be nil?

Leave a Reply