How to create a Fetch Request in the Xcode Model Editor

You can create Fetch Requests in the Xcode model editor, including a Predicate. These are somewhat easier to setup. To create one, select your .xcdatamodeld file, then head over to Editor – Add Fetch Request. Give it a catchy name and a filter property, and much of the above code becomes obsolete.

Here’s how you can retrieve one of those in code:

    // create a fetch request from template
    NSFetchRequest *fetchRequest = [self.managedObjectModel fetchRequestTemplateForName:@"MyFetch"];
    NSArray *fetchedObjects = [self.managedObjectContext executeFetchRequest:fetchRequest error:nil];
    for (Event *event in fetchedObjects) {
        NSLog(@"%@", [event.timeStamp description]);

Note that to retrieve your Fetch Request Template you need a reference to your Managed Object Model as well as your context. The easiest way to grab hold of it in an iOS app is to pass it in on a property, just like we did with self.managedoObjectContext.

One thought on “How to create a Fetch Request in the Xcode Model Editor

  1. Using this with an NSFetchedResultsController I ran into a problem: Xcode displayed the error “Can’t modify a named fetch request in an immutable model”. The solution is to create a mutable copy when creating the fetch request, like so:

    NSFetchRequest *fetchRequest = [[self.managedObjectModel fetchRequestTemplateForName:@"myFetch"]copy];

    Thanks to Tim Dean for mentioning this on Stack Overflow:

Leave a Reply