Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I have a NSFetchedResultsController in every view?

I'm using Core Data in my first iPhone application and trying to understand NSFetchedResultsController. It works great in my root view. Do I need to instantiate an instance in every one of my view controllers? If so, is there a template that makes this as easy as it was in my root controller (I just checked a box in the template when creating the project). When I add a single new view controller I don't see an option to use Core Data.

Update: Even after I did cut/paste the code into my second view, it took me a while to realize that I also needed to set the managedObjectContext before switching to the new view. I added the following line to my RootViewController before pushing the new view on the navigation stack:

self.newVC.managedObjectContext = self.managedObjectContext;
like image 386
Jeremy Mullin Avatar asked Feb 07 '10 23:02

Jeremy Mullin


People also ask

When should we use NSFetchedResultsController class?

NSFetchedResultsController is a very useful class provided by the CoreData framework. It solves many performance issues you frequently run into while reading a large amount of data from database and displaying that data using a UITableview, UICollectionView or MKMapView.

What is NSFetchedResultsController?

A controller that you use to manage the results of a Core Data fetch request and to display data to the user.


2 Answers

If your other views are visualizing different Entities, then yes, you would use a different NSFetchedResultsController. You can basically get away with copy-and-pasting the code from the autogenerated root view controller for your other view controllers... just change the Entity name.

However, if the other (table) views down your hierarchy are just displaying different attributes of the same Entity, it's more efficient/simpler to just pass the existing NSFetchedResultsController object down the hierarchy. Just create a NSFetchedResultsController member in the class interface and expose it as a property in the view controller's .h file, and then synthesize the property and release it in its .m file. Then set the property before you push the view controller on the stack.

like image 87
Shaggy Frog Avatar answered Nov 09 '22 09:11

Shaggy Frog


I'd like to add that if you are using multiple NSFetchedResultsControllers for the same entity, but in different tables, your UITableView will not update if you insert data for the same entity using another controller. This is because your UITableView will not receive willChangeContent ,etc messages from an NSFetchedResultsController for which you have not set yourself as a delegate.

like image 39
Alex Stone Avatar answered Nov 09 '22 08:11

Alex Stone