Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why i should use the NSManagedObjectContext's perform() and performAndWait() while i can use DispatchQueue.global

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*/ 
}
like image 598
Mohamed Mohsen Avatar asked Jan 22 '26 22:01

Mohamed Mohsen


1 Answers

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.

like image 70
Mateus Forgiarini da Silva Avatar answered Jan 25 '26 10:01

Mateus Forgiarini da Silva



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!