Database Reference
In-Depth Information
NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:@
"name"
ascending:YES];
[fetchRequest setSortDescriptors:[NSArray arrayWithObject:sort]];
In this example, we are retrieving all the
Recipe
entities by creating an
NSFetchRequest
with the
NSEntityDescription
set to our entity and no predicate.
However, in addition to fetching the
Recipe
entities, we also want them sorted.
We accomplish the sorting by adding an
NSArray
of
NSSortDescriptor
instances
directly to the
NSFetchRequest
, which cause the returned
NSArray
to be properly
sorted.
The
NSSortDescriptor
takes two parameters as part of its
-init
: a key and a
BOOL
denoting whether the sort is ascending or descending. We can have as many
NSSortDescriptor
objects as we want as part of the sort, and therefore they are
placed within an
NSArray
prior to the sort being performed.
Adding an
NSSortDescriptor
is especially useful on Cocoa Touch because the
NSFetchedResultsController
continues to keep its results sorted without any inter-
vention on our part. The
NSFetchedResultsController
is discussed in more depth in
Chapter 2,
iOS: NSFetchedResultsController
, on page 23
.
1.7
Fetched Properties
In addition to
NSFetchRequest
objects, we have the ability to define a lazy rela-
tionship between objects. Fetched properties are kind of a cross between
relationships and the
NSFetchRequest
. A fetched property is not a relationship
in the strictest sense and is not realized until the property is requested. When
the property is accessed, Core Data performs the underlying
NSFetchRequest
and returns the result. Unlike a normal relationship, a fetched property is
returned as an
NSArray
as opposed to an
NSSet
.
In practice, I have found fetched properties to be less useful and less flexible
than either creating a stored fetch request or building the fetch request in
code. Usually when a situation calls for a fetched property, it tends to be
easier to subclass the entity in question, perform an
NSFetchRequest
in code,
and return the results.
1.8
Wrapping Up
We covered a large number of the important pieces of Core Data in this
chapter. As we continue to explore Core Data in depth, please use this
chapter as a reference point for the aspects of Core Data and how they all fit
together. By the end of the topic, each of these elements should be very
familiar to you.