views:

269

answers:

2

I'm new to this Core Data business.

I got a UITableViewController hooked up with a NSFetchedResultsController. In viewDidLoad, I fire a request to get necessary data from the server, then use [self.fetchedResultsController performFetch:&error] to update the table view. All works fine until that point.

Now I want to move the data fetching stuff to another thread, so after the app received a NSArray object from the server, it performs the didFinishFetchingItems selector on the main thread. In that selector, I save the NSArray to the Core Data store and have the fetchedResultsController perform a fetch. No data show up, although a NSLog reveals that the data is still there (e.g. [[fetchedResultsController fetchedObjects] count] returns 100). I have to put a [self.tableView reloadData] at the end of the method to refresh the table view manually.

My question is: What have I done wrong? Why did I need to do the table view refreshing manually?

+1  A: 

You do not need to refresh anything manually; fetchedResultsController does that for you.

What you need to do is to implement NSFetchedResultsControllerDelegate for some object, and set that object as the delegate for your fetchedresultscontroller.

See this about what you need to implement. If your model is simple, you can pretty much copy-paste that code into your delegate and everything works.

The important thing is to keep both the resultscontroller and other pieces of code working against the same managed object context. This is how the resultscontroller can pick up the changes. But, in Core Data guide, there are some caveats about multithreading, so make sure you have your threading bases covered and then all works.

Jaanus
I think the problem is with my multi threading code, since I don't have to reload the table view manually when operating in a single thread. Haven't found out what's wrong with it, though.
QAD
A: 

You should not touch your NSFetchedResultsController in a non-main thread, that is not a thread-safe operation.

If you are having a long delay on fetching then you need to do a background fetch using a separate NSManagedObject. If you perform a separate fetch in the background it will load the data into cache and then the NSFetchedResultsController will hit the cache instead of disk, speeding up retrieval on the main thread.

Marcus S. Zarra