Database Reference
In-Depth Information
class ViewController: UIViewController ,
NSFetchedResultsControllerDelegate {
This simply tells the compiler that the ViewController class will implement some of
the fetched results controller's delegate method.
Now go back to viewDidLoad and set the view controller as the fetched results
controller's delegate. Add the following line of code after you initialize the fetched
results controller:
fetchedResultsController . delegate = self
That's all you need to start monitoring changes! Of course, the next step is to do
something when those change reports come in. You'll do that next.
Note: A fetched results controller can only monitor changes made via the
managed object context specified in its initializer. If you create a separate
NSManagedObjectContext somewhere else in your app and start making
changes there, your delegate method won't run until those changes have been
saved and merged with the fetched results controller's context.
Responding to changes
First, remove the reloadData call from tableView(_:didSelectRowAtIndexPath:) . As
mentioned before, this was the brute force approach that you're now going to
replace.
NSFetchedResultsControllerDelegate has four methods that come in varying
degrees of granularity. To start out, implement the broadest delegate method, the
one that says: “Hey, something just changed!”
Add the following new method:
func controllerDidChangeContent(controller:
NSFetchedResultsController ) {
tableView . reloadData ()
}
The change may seem small, but implementing this method means that any change
whatsoever, no matter the source, will refresh the table view.
Build and run the application. Verify that the table view's cells still update correctly
by tapping on a few cells:
Search WWH ::




Custom Search