Search code examples
iosswiftcore-datansmanagedobjectcontextdispatch-async

NSMangedObjectContext performBlock in background issue


I read this article to save objects in Core Data database in background.

In the end of the article they have this code to save data in background:

[temporaryContext performBlock:^{
   // do something that takes some time asynchronously using the temp context

I understand that if we use performBlock the operation will be done asynchronously, but in what queue? Do I need to put it in background thread like this:

dispatch_async(dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0), { () -> Void in
            temporaryContext.performBlock({ () -> Void in

            })
        })

or it's enough to use:

temporaryContext.performBlock({ () -> Void in

                })

Solution

  • It is enough to use:

    temporaryContext.performBlock({ () -> Void in
    
    })
    

    Your code will be invoked in a queue associated with a temporaryContext. The temporaryContext is a NSManagedObjectContext which has its own private queue (NSPrivateQueueConcurrencyType)