1

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")
        })
    }
}
4

1 回答 1

0

是因为group.wait()来电。 group.wait()将阻塞当前线程并且 context.perform 也将尝试在同一线程上运行。

于 2019-04-12T07:49:55.597 回答