Database Reference
In-Depth Information
CHAPTER
2
iOS: NSFetchedResultsController
The
NSFetchedResultsController
was introduced alongside Core Data when the
framework was added to iOS with version 3.0. Since its introduction, develop-
ers have settled into a love-hate relationship with this class. When it is used
in the way it was intended, it works extremely well. The hate part comes in
when developers attempt to use the
NSFetchedResultsController
outside of its
intended niche—that is when things start to fall apart quickly.
In this chapter, we discuss what the
NSFetchedResultsController
is designed to do
and how it works. Once we have a handle on how it works, we'll explore
alternatives so you know what to use when
NSFetchedResultsController
is not the
correct fit.
2.1
How to Use the NSFetchedResultsController
When Core Data was added to iOS, it was clear to the Core Data team that
Core Data and the
UITableView
would be used together extensively. They also
realized that getting these two pieces to work together smoothly would require
a fair amount of code that could be abstracted away; that abstraction is the
NSFetchedResultsController
. The
NSFetchedResultsController
is the glue that binds a
UITableView
to Core Data so that we need to write very little code.
The purpose of the
NSFetchedResultsController
is twofold. First, the
NSFetched
-
ResultsController
is designed to retrieve data from Core Data and store that data
for access. It does this with an internal
NSFetchRequest
that it uses for the
retrieval. It then stores the data and makes it available for use. As part of the
storage and retrieval, the
NSFetchedResultsController
organizes the returned data
into sections, in the process making the data more useful to a
UITableView
.
The
NSFetchedResultsController
's second purpose is to monitor changes in the data.
Without the ability to be notified when the data has changed, the
NSFetched
-
ResultsController
would not be much more use than an
NSArray
. When the