如何在 Swift 中更改核心数据的并发类型

How to change the concurrency type for Core Data in Swift

如今,当您创建 SwiftUI 核心数据应用程序时,Xcode 会创建此结构。

import CoreData

struct PersistenceController {
  static let shared = PersistenceController()
  
  static var preview: PersistenceController = {
    let result = PersistenceController(inMemory: true)
    let viewContext = result.container.viewContext
    return result
  }()
  
  var context:NSManagedObjectContext {
    return container.viewContext
  }
  
  var container: NSPersistentContainer
  
  init(inMemory: Bool = false) {
  
    
    container = NSPersistentContainer(name: "PharmaTrac")
    container.newBackgroundContext()

    if inMemory {
      container.persistentStoreDescriptions.first!.url = URL(fileURLWithPath: "/dev/null")
    }
    container.loadPersistentStores(completionHandler: {(storeDescription, error) in
      if let error = error as NSError? {
        // Replace this implementation with code to handle the error appropriately.
        // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
        
        /*
         Typical reasons for an error here include:
         * The parent directory does not exist, cannot be created, or disallows writing.
         * The persistent store is not accessible, due to permissions or data protection when the device is locked.
         * The device is out of space.
         * The store could not be migrated to the current model version.
         Check the error message to determine what the actual problem was.
         */
        fatalError("Unresolved error \(error), \(error.userInfo)")
      }
    })
  }
}

我想将上下文并发类型更改为私有队列,就像这样

var managedObjectContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)

但是 apple 以这种方式创建它,上下文是自动创建的。

如何使用 .privateQueueConcurrencyType 创建上下文?

该代码创建一个 NSPersistentContainer,然后从容器中获取 viewContext。如果需要,容器还可以创建其他上下文。您可以调用 container.newBackgroundContext() 来创建一个新的上下文,就像您描述的那样(它将使用私有队列并发)。您还可以使用 context.performBackgroundTask(_:) 让容器为一些后台工作动态创建一个新的私有队列上下文。