Database Reference
In-Depth Information
NSManagedObjectContext *moc = [self managedObjectContext];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:@
"Recipe"
inManagedObjectContext:moc]];
In this example code, we construct a new
NSFetchRequest
and call
-setEntity:
on
it. We use the class method
+entityForName:inManagedObjectContext:
on the
NSEntity-
Description
class to get the appropriate instance of
NSEntityDescription
back for the
setter.
Executing a Fetch Request
Once we have constructed our
NSFetchRequest
, we need to execute it against
the
NSManagedObjectContext
to get the results. Like a result set when accessing
a database, an executed
NSFetchRequest
will return an
NSArray
of entities
matching our search criteria. Since it is possible that a search might fail, the
execution of an
NSFetchRequest
accepts a pointer to an
NSError
to describe any
problems that resulted from the execution. For example, if we want to execute
the fetch from the previous example, we use the following code:
NSManagedObjectContext *moc = [self managedObjectContext];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:@
"Recipe"
inManagedObjectContext:moc]];
NSError *error = nil;
NSArray *results = [moc executeFetchRequest:request error:&error];
if
(error) {
NSLog(@
"Error: %@\n%@"
, [error localizedDescription], [error userInfo]);
return
;
}
In this example, we call
-executeFetchRequest:error:
on the
NSManagedObjectContext
,
passing in the
NSFetchRequest
and a pointer to a local
NSError
. If the fetch failed
with an error, the pointer will be directed to an instance of
NSError
that
describes the problem, and the
NSArray
will be assigned to
nil
. In that situation,
we dump the error to the console and return. If there is no error, we can
proceed with our code. Note that the
NSArray
is guaranteed to not be
nil
at this
point, but it could be empty if no results are returned.
NSPredicate
When we don't want every instance of an entity returned, we use an
NSPredicate
to narrow the search or filter the results. The
NSPredicate
class is quite complex
and powerful and can be used for more things than just Core Data. It is fre-
quently used to filter the results of collection classes by acting on the KVC
API and doing logic checks on the objects contained in the
NSArray
or
NSSet
.