Database Reference
In-Depth Information
One of the most common ways to use an
NSPredicate
is to construct a
SQL
-like
query, such as the following example:
NSManagedObjectContext *moc = [self managedObjectContext];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:@
"Recipe"
inManagedObjectContext:moc]];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@
"serves > 10"
];
[request setPredicate:predicate];
There are many different ways to build an
NSPredicate
. The one shown in the
previous example accepts a
SQL
-like
NSString
and can accept any number of
parameters after the
NSString
. For example, if we were going to pass in the
number of servings, we would rewrite the
NSPredicate
as follows:
NSUInteger numberOfServings = 10;
NSManagedObjectContext *moc = [self managedObjectContext];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:@
"Recipe"
inManagedObjectContext:moc]];
NSPredicate *predicate = nil;
predicate = [NSPredicate predicateWithFormat:@
"serves > %i"
, numberOfServings];
[request setPredicate:predicate];
It is possible to add as many parameters to the
NSPredicate
as needed.
The
NSPredicate
class is quite flexible and can be used in a large number of
ways. For further reading on how to use the class to its full potential, I recom-
mend Apple's
Predicate Programming Guide
.
1
Stored Fetch Requests
In addition to constructing the
NSFetchRequest
directly in code, it is possible to build
them within the data model and store them for later use. By storing the fetch
requests within the model itself, it is possible for us to change them as needed
without having to go through all the code looking for every place that it is used.
Simply changing it in the model will automatically update wherever it is being
used. To store an
NSFetchRequest
within the data model, we select the entity that
we want to run the request against and choose Design > Data Model > Add Fetch
Request from the main menu. From there we will be able to set the name of the
fetch request and define its predicate, as shown in
Figure 5,
Stored fetch request
,
on page 20
.
Once we have the fetch request in our data model, we can request a reference
to it by asking the
NSManagedObjectModel
. Once we have a reference to the