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;
}




Jay is the CEO and founder of WP Hosting, a boutique style managed WordPress hosting and support service. He has been working with Plesk since version 9 and is a qualified Parallels Automation Professional. In his spare time he likes to develop iOS apps and WordPress plugins, or draw on tablet devices. He blogs about his coding journey at http://wpguru.co.uk and http://pinkstone.co.uk.