I’m working on a project where I many view controllers and each one it is based on Core data and UITableView. I have problem with saving, when we editing table we should store current info and data. Next if user tapped ‘Save button everything should go into masterContext in appDelegate class (and only then, so we couldnt save dynamicaly in masterContext!).
My question is the following. How can I save current data if the user has tapped the save button passing it to the masterContext? Should I create temporaryContext and than merge it with masterContext?
Thanks for your answers.
Based on your question, you don’t need to have multiple contexts and then share their changes with the master one. Use only a master context that you share among different controllers. Usually this is ok.
Here two approaches are valid.
The first approach means that you can pass the context among controllers as a sort “of code injection”.
where
masterContextis astrongproperty forcontroller1.The second approach means that in the class where you set up the Core Data stack (usually the application delegate) you provide a
readonly propertythrough which you can access the context. You can also provide asavemethod to save the context. I don’t like very much to put all the set up code in the application delegate and so, I usually create a singleton class for this purpose. DCTCoreDataStack is an example of this.@MarcusZarra in PASSING AROUND A NSMANAGEDOBJECTCONTEXT ON IOS shows also some techniques to pass the context around.
If are interested in you can also use new iOS 5 APIs in Core Data and set up a master context that works in a private queue (
NSPrivateQueueConcurrencyType) and a child that works on the main thread (NSMainQueueConcurrencyType). This is called parent/child context. Changes done in the main thread are passed to the master that will save changes in the CD store. Here some notes. Core Data Release Notes. In addition take a look at Multi-Context CoreData for a complete explanation.