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*/
}
Because perform and performAndWait guarantee that you will access the objects in the context they were created.
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.
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