Database Reference
In-Depth Information
Something to note here is that along with passing in
@"type"
to the initialization
of the
NSFetchedResultsController
, we also added a second
NSSortDescriptor
to the
NSFetchRequest
. The
NSFetchedResultsController
requires the data to be returned in
the same order as it will appear in the sections. As a result, we must sort the
data first by
type
and then by
name
.
cacheName
The last property of the initialization of the
NSFetchedResultsController
is the
cacheName
. This value is used by the
NSFetchedResultsController
to build up a small
data cache on disk. That cache will allow the
NSFetchedResultsController
to skip
the
NSPersistentStore
entirely when its associated
UITableView
is reconstructed.
This cache can dramatically improve the launch performance of any associated
UITableView
.
However, this cache is extremely sensitive to changes in the data and the
NSFetchRequest
. Therefore, this cache name cannot be reused from one
UITableView
to another, nor can it be reused if the
NSPredicate
changes.
Once the
NSFetchedResultsController
has been initialized, we need to populate it
with data. This can be done immediately upon initialization, as in our current
example, or it can be done later. When to populate the
NSFetchedResultsController
is more of a performance question. If the associated
UITableView
is constructed
very early, we may want to wait to populate the
NSFetchedResultsController
until
the
UITableView
is about to be used. For now and until we can determine there
is a performance issue, we will populate it upon initialization. This is done
with a call to
-performFetch:
, which takes a pointer to an
NSError
variable. If there
is an error in the fetch, the
NSError
will be populated, and the call will return
NO
. This is a perfect place to use our
ZAssert
macro, which is discussed in
depth in
Appendix 2,
Macros in the Precompiled Header
, on page 221
.
Wiring the NSFetchedResultsController to a UITableView
Now that we have our
NSFetchedResultsController
initialized, we need to wire it into
its associated
UITableView
. We do this within the various
UITableViewDatasource
methods.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return
[[[self fetchedResultsController] sections] count];
}
The first one is
-numberOfSectionsInTableView:
. Here we ask the
NSFetchedResultsController
to return its array of sections, and we return the count of them. If we don't