My app connects to a webservice, performs POST from 3 different methods and inserts each of these 3 sets of data to Core Data. Everytime new data is available everything in core data gets deleted and new data is inserted. Each of these 3 methods are displayed in different TableViewControllers
, which means more than 3 Fetches everytime each of these TableViewControllers
are displayed.
Wrapping things up, we have 3 sets of data that are fetched from a webservice, and then i insert all these into different entities while fetching new data to display in the main TableViewController
.
Now i am struggling with the complex relation of threads and multi-context Core Data structure. Where should i perform the insert, delete and fetch to ensure the thread safety of my application?
Do your UI fetches on the main thread from the main context.
For your importing, don't run the session callback on the main thread, run it on any background queue. Create a new private context and set main as its parent. In the session callback use the block interface to import and save the background context and then its parent (again, using the block interface).
In multi-context CoreData, You can have a privateQueueRootMOC and a mainQueueRootMoc, the main MOC is used to fetch data in mainThread, the private MOC is Used to update, insert and delete data in privateMOC thread.
privateMOC.performBlock({ () -> Void in
//try insert, delete, update
....
try privateMOC.save()
onCompleteBlock() //fetch data in main thread use main MOC
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With