Swift 3.0 CoreData创建多个上下文

Ole*_*huk 2 core-data ios swift swift3

以前在应用程序中我使用多上下文方法来使用后台上下文来操作后台线程中的数据.这是这样做的.

 // backgroundContext in the background thred
    lazy var backgroundContext: NSManagedObjectContext? = {
        let coordinator = self.store.persistentStoreCoordinator
        var backgroundContext = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType)
        backgroundContext.persistentStoreCoordinator = coordinator
        return backgroundContext
    }()
Run Code Online (Sandbox Code Playgroud)

它是这样使用的:

self.coreDataManager.saveContext(self.coreDataManager.backgroundContext!)
Run Code Online (Sandbox Code Playgroud)

如何使用新的CoreData更新我们应该处理多个CoreData上下文?因为现在NSPersistentContainer它应该以另一种方式处理.

Rey*_*eon 5

根据此处提供的Apple自己的文档以及Core Data中的新内容,这是推荐的方法:

let container = NSPersistentContainer.persistentContainerWithName("myApp")
container.performBackgroundTask() { (moc) in
    // use moc to do asynchronous work
}
Run Code Online (Sandbox Code Playgroud)

默认情况下,NSPersistentContainer为UI相关任务提供上下文ViewContext,并且可以通过执行以下操作来创建可能需要的背景上下文:

let moc = container.newBackgroundContext

但请注意,在谈话中他们建议使用performBackgroundTask()而不是创建自己的背景上下文.这是因为如果您自己使用上下文,则所述方法会执行一些不会发生的优化.