Database Reference
In-Depth Information
var
error:
NSError
? =
nil
if
(!
fetchedResultsController
.
performFetch
(&error)) {
println
(
"Error:
\(error?.
localizedDescription
)
"
)
}
Setting up a fetched results controller is a little more complicated than setting up a
simple fetch request. Let's go step by step through the process:
1. The fetched results controller handles the coordination between Core Data and
your table view, but it still needs you to provide an
NSFetchRequest
. Remember
that the
NSFetchRequest
class is highly customizable. It can take sort descriptors,
predicates, etc.
In this example, you simply initialize a fetch request with an entity description,
because you want to fetch all
Team
objects.
2. The initializer method for a fetched results controller takes four parameters: first
is the fetch request you just created.
The second parameter is an instance of
NSManagedObjectContext
. Like
NSFetchRequest
, the fetched results controller class needs a managed object
context to execute the fetch. It can't actually fetch anything by itself.
The other two parameters are optional:
sectionNameKeyPath
and
cacheName
. Leave
them blank for now; you'll read more about them later in the chapter.
3. You execute the fetch request. If there's an error, you log the error to the
console.
Note that fetching with
NSFetchRequest
returns an array of results. Fetching with
NSFetchedResultsController
returns a Boolean to denote success or failure. Wait a
minute... where are your fetched results?
NSFetchedResultsController
is both a wrapper around a fetch request
and
a
container for its fetched results. You can get at them either with the
fetchedObjects
property or the
objectAtIndexPath
method.
Next, you'll connect the fetched results controller to the usual table view data
source methods. The fetched results determine both the number of sections and the
number of rows per section.
With this in mind, re-implement
numberOfSectionsInTableView
and
numberOfRowsInSection
, as shown below:
func
numberOfSectionsInTableView
(tableView:
UITableView
) ->
Int
{
return
fetchedResultsController
.
sections
!
.
count
}
func
tableView(tableView:
UITableView
,
numberOfRowsInSection section:
Int
) ->
Int
{