How to create a Fetched Results Controller

The NSFetchedResultsController makes populating UITableViews a breeze. I keep forgetting how to set those up, so here’s a quick list on how to create those:

  • create a Fetch Request
  • create the Fetched Results Controller with the Fetch Reuqest
  • execute the Fetch

The Fetch Request itself needs:

  • a Managed Object Model
  • an Entity Name (i.e. what to fetch)
  • an optional Template if created visually
  • an optional array of Sort Descriptors

Here’s a custom initialiser that first creates a Fetch Request, adds this to a Fetched Results Controller and finally executes the fetch.

-(NSFetchedResultsController *)fetchedResultsController {
    
    if (!_fetchedResultsController) {
        
        // create fetch request from template
        NSFetchRequest *fetchRequest = [[self.managedObjectModel fetchRequestTemplateForName:@"Books"]copy];
        
        // define a sort descriptor
        NSSortDescriptor *descriptor = [[NSSortDescriptor alloc]initWithKey:@"airDate" ascending:YES];
        NSArray *descriptorArray = [[NSArray alloc]initWithObjects:descriptor, nil];
        fetchRequest.sortDescriptors = descriptorArray;
        
        // create the controller
        _fetchedResultsController = [[NSFetchedResultsController alloc]initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:nil];
    }
    
    // execute the fetch
    [_fetchedResultsController performFetch:nil];
    
    return _fetchedResultsController;
}




2 thoughts on “How to create a Fetched Results Controller

Leave a Reply