Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct thread to perform delete, insert and fetch from/to Core Data

Tags:

ios

core-data

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?

like image 850
Rashid Avatar asked Jul 23 '16 13:07

Rashid


2 Answers

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).

like image 112
Wain Avatar answered Sep 28 '22 06:09

Wain


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
})
like image 43
Hao Avatar answered Sep 28 '22 05:09

Hao