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?
3 Answers
Answers 1
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).
Answers 2
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 })
Answers 3
Maybe you should check this article, which compares 3 ways to do background work with Core Data : http://floriankugler.com/2013/04/29/concurrent-core-data-stack-performance-shootout/
0 comments:
Post a Comment