FetchRequest Template

I had been using core data fetch request for a long time and while browsing about the fetch request, I came across a feature called Fetch Request Template.

This blog describes about the  FetchRequestTemplate in detail.

What is Fetch Request Template :

Fetch request templates allow to pre-define queries and their parameters in the model (with the tool) – typically they contain variables that need to be substituted at runtime.

How It Works :

Let have a model with the entity student and attributed listed below :


Step 1 : Create the Template

Approach 1:

NSManagedObjectModel *model = // reference to model
NSFetchRequest *requestTemplate = [NSFetchRequest new];
NSEntityDescription *entityDescription = [[model entitiesByName] objectForKey:@“Student”];
[requestTemplate setEntity:entityDescription]; 
NSPredicate *predicateTemplate = [NSPredicate predicateWithFormat: @”(name like[cd] $NAME) AND  (age > $AGE)”];
[requestTemplate setPredicate:predicateTemplate];
[model setFetchRequestTemplate:requestTemplate forName:@“StudentWithNameWithAge”];

Approach 2:

Go to your model (xcdatamodel) file, then Editor -> Add Fetch Request. The UI makes it easy to write a complex fetch request. Unlike the previous approach, you cannot store things like sort descriptors. You’d have to add those after you retrieve the template.


Step 2 : Access the Template

NSManagedObjectContext *moc = // reference to context
NSManagedObjectModel *model = // reference to model  
NSError *error = nil;
NSDictionary *substitutionDictionary = [NSDictionary dictionaryWithObjectsAndKeys: myName, @“NAME”,  age, @“AGE”, nil];
NSFetchRequest *fetchRequest = [model fetchRequestFromTemplateWithName:@“StudentWithNameWithAge”  substitutionVariables:substitutionDictionary];
NSArray *results = [moc executeFetchRequest:fetchRequest error:&error];
// Process results

Points to Consider :

1If the template contains a predicate with substitution variables, you should instead use
fetchRequestFromTemplateWithName:substitutionVariables: to create a new fetch request.

2If you use fetchRequestFromTemplateWithName:substitutionVariables:. The variables dictionary must provide values for all the variables. If you want to test for a nil value, use [NSNull null].  This method provides the usual way to bind an “abstractly” defined fetch request template to a concrete fetch.

3If you use  setFetchRequestTemplate:forName:. This method raises an exception if the receiver has been used by an object graph manager.

Happy Coding….

iOS Developer,
Mallow Technologies.

Leave a Comment

Your email address will not be published. Required fields are marked *