views:

147

answers:

1

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;
+2  A: 

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.

Shaggy Frog
Thanks. I'm visualizing a different entity. Does XCode do anything to make it easier, or do I really have to cut/paste that code for every view? I know it isn't a big deal, but I have to grab the definitions out of the header, and the implementation from the m file. Kind of a pain.
Jeremy Mullin
You've really got to cut and paste for every view. Either that, or create another class to abstract away the interaction with the fetched results controller. I've tried that once, though, and I would have been much better off just dealing directly with the fetched results controller.
kubi
Like kubi says, abstracting away some of the detail here may or may not be efficient, depending on the number of different Entities you need to visualize. If it's 2 or 3, copy-and-paste. If it's 10, maybe abstraction starts to save you time. Or maybe if this code's going to be reused a lot more later, that also suggests keeping it clean from the beginning. Be pragmatic here and make the call based on your domain and your requirements, and not a strict adherence to the DRY principle.
Shaggy Frog