views:

102

answers:

1

I'm building an app with two tabs. The first tab has a main tableview that connects to a detail view of the row. The second tab will display a tableView based on the user adding content to it by tapping a button on the detail view.

My question is this. What is the correct design pattern to do this? Do I create a second ManagedObjectContext/ManagedObjectContextID then save that context to a new persistent store or can the MOC be saved to the existing store without affecting the original tableview?

I've looked at CoreData Recipes and CoreData Books and neither deal with multiple stores although books does deal with multiple MOC's. Any reference would be great.

+1  A: 

A single NSManagedObjectContext is more than sufficient for this design. What you want to do is implement the dependency injection design pattern. What this translates to is that when you create each of your tabs, you pass the singular NSManagedObjectContext instance into each of them. Each NSViewController is then responsible for accessing the NSManagedObjectContext as needed.

update

If you are seeing the same data then that is an issue with your 'NSFetchedResultsController' and not the 'NSManagedObjectContext'. The 'NSManagedObjectContext' has access to all of the data, the 'NSFetchedResultsController' is what does all of the filtering based on it's 'NSFetchRequest'.

Perhaps you should post the 'NSFetchedResultsController' for each of your controllers (by editing your question here) so that we can see what is going on.

update

The MOC does not get destroyed, at all, ever. You simply have more than one reference/pointer to the same MOC. The MOC is the scratchpad for the NSManagedObject instances that you are accessing. When you call -save: on that MOC, it takes the changes in that scratchpad and persists them out to disk.

Except in some very, highly unusual, situations, you only ever need one MOC per thread. In your design that you have described so far, one MOC is more than sufficient.

Marcus S. Zarra
I tried what you are suggesting and ended up with all the data on the first tab/tableViewController on the second tab/tableViewController. I'm sure this is because I incorrectly passed in the MOC from the AppDelegate instead of the detailedView. Have I got this right? Do I just set the MOC from here and save and merge the changes? This seems too simple to be true.
Jim
Thanks for the update. I've added the NSFetchedResultsController and now have the selection of items correctly displayed in the FavouritesViewController class that I want to also save to this classes tableView. I'm still unclear how the MOC saves this without destroying the original MOC which I still needed for the RootViewController. Does this really not need another MOC or persistent store for the FavouritesViewController to access? It's difficult to know which code would be appropriate to post.
Jim