3

I have some confusion about run the CoreData code on the background queue.

There is some methods we can use to perform a CoreData code on the background thread using the NSManagedObjectContext.

viewContext.perform { /*some code will run on the background thread*/ }
viewContext.performAndWait{ /*some code will run on the background thread*/ }

My question here why i should use these functions rather than using the ordinary way for running some code on the background thread using the DispatchQueue

DispatchQueue.global(qos: .background).async { 
     /*some code will run on the background thread*/ 
}
Mohamed Mohsen
  • 167
  • 1
  • 13

1 Answers1

4

Because perform and performAndWait are thread safe.

Let's say you have two contexts.

let privateContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
let mainContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)

By using perform or performAndWait you guarantee that they are executed in the queue they were created. Otherwise, you will have problems with concurrency.

So you can get the behavior below.

DispatchQueue.global(qos: .background).async {
        //some code will run on the background thread
        privateContext.perform {
            //some code will run on the private queue
            mainContext.perform {
                //some code will run on the main queue
            }
        }
    }

Otherwise, they will all be executed in the background as pointed out in the following code.

DispatchQueue.global(qos: .background).async {
        //some code will run on the background thread
            do {
                //some code will run on the background thread
                try privateContext.save()
                do {
                    //some code will run on the background thread
                    try mainContext.save()
                } catch {
                    return
                }
            } catch {
                return
            }
        }

To get to know more about concurrency, here there is a link to Apple documentation.