I'm just started working on a new project and thought I'd try out Core Data's NSPersistentContainer
instead of writing my own stack.
I just stumbled upon this issue where calling the perform
method of the managedObjectContext
actually does nothing if the task was started as part of NSPersistentContainer
's performBackgroundTask
.
Here's a snippet of what I'm currently doing to demonstrate the issue. Note that I have a DispatchGroup
to ensure that the tasks are performed in sequence.
// DataImporter.swift
class func importData(url: URL, context: NSManagedObjectContext, completion: () -> ()) {
context.perform {
// Code inside here never gets call
DispatchQueue.main.async(execute: {
completion()
})
}
}
// ViewController.swift
func multipleImportTasks() {
persistentContainer.performBackgroundTask { managedObjectContext in
let group = DispatchGroup()
group.enter()
let fileUrl1 = Data(someData)
DataImporter.importData(fileUrl1, context: managedObjectContext, completion: {
group.leave()
})
group.wait()
group.enter()
let fileUrl2 = Data(someData)
DataImporter.importData(fileUrl2, context: managedObjectContext, completion: {
group.leave()
})
group.notify(queue: DispatchQueue.main, execute: {
print("all done")
})
}
}