So far, we've been implementing viewDidAppear
to handle refreshing our data, but the process (fetch, pass, reload) could be a little overkill. Also, what happens if we can't rely on viewDidAppear
being called? Fortunately, there's a more sophisticated solution for refreshing our [core]data called NSFetchedResultsController
.
To be vague, the controller intelligently feeds data to a tableView, only updating it when there are changes. To be more specific, it fires off delegate methods when the results of it's fetch change. Like most other Core Data things, there's a buncha boilerplate for implementing these delegate methods (which we provide). If you want to read more about how it works, check out the Apple docs.
Let's integrate NSFetchedResultsController
into good ol' slapChat.
Set it up so we can add new messages to our tableView without going to a different view controller, creating a situation where we can't rely on viewDidAppear
for refreshing.
FISMessage
.
content
to a string version of the current time.viewDidAppear
; we won't be needing it anymore :DWe're going to set up the results controller within our tableView controller for a few reasons. First, you can only set the NSFRC's delegate (which you need) once. Second, Apple warns against changing NSFRC's fetch request or predicates post-initialization, so we want to set them up per view controller. Last but not least, we want our view controllers to be as self-contained as possible.
NSFetchedResultsController
property to your tableView controller.viewDidLoad
, initialize it using initWithFetchRequest:managedObjectContext:sectionNameKeyPath:cacheName:
nil
for both sectionNameKeyPath:
and cacheName:
.m
and check out the boilerplate NSFetchedResultsControllerDelegate
implementation we included.
Read through the methods to see how they will handle changes. Also uncomment them.fetchedResults
property (a prime example of good naming conventions!). Remove your local messages array entirely and replace it in the data source with your NSFRC's array.performFetch:
on your NSFRC at the end of viewDidLoad
.
nil
for the argument, we'll get to how NSError
's work later on.View SlapChat Fetched (Results Controller) on Learn.co and start learning to code for free.