如果您使用 Apple 作为初创公司提供的标准 PersistentController,您可以尝试使用
.environment(\.managedObjectContext, privateContext)
您的View 需要此属性才能使其工作。 @State 不应该是必要的,因为更改是在后台通过通知等其他方式完成的。
let privateContext = PersistenceController.shared.container.newBackgroundContext()
调用 newBackgroundContext() 方法会导致持久化容器创建并返回一个新的 NSManagedObjectContext,concurrencyType 设置为 NSManagedObjectContextConcurrencyType.privateQueueConcurrencyType。这个新上下文将直接与 NSPersistentStoreCoordinator 关联,并设置为自动使用 NSManagedObjectContextDidSave 广播。
然后使用 Apple 提供的大部分示例代码对其进行测试。
struct SampleSharedCloudKitApp: App {
let privateContext = PersistenceController.shared.container.newBackgroundContext()
var body: some Scene {
WindowGroup {
VStack{
Text(privateContext.description) //Added this to match with ContentView
ContentView()
.environment(\.managedObjectContext, privateContext)
//Once you pass the privateContext here everything below it will have the privateContext
//You don't need to connect it with @FetchRequest by any other means
}
}
}
}
struct ContentView: View {
@Environment(\.managedObjectContext) private var viewContext
@FetchRequest(
sortDescriptors: [NSSortDescriptor(keyPath: \Item.timestamp, ascending: true)],
animation: .default)
private var items: FetchedResults<Item>
var body: some View {
List {
Text((items.first!.managedObjectContext!.concurrencyType == NSManagedObjectContextConcurrencyType.privateQueueConcurrencyType).description) //This shows true
Text(items.first!.managedObjectContext!.description)// This description matches the parent view
Text(viewContext.description)// This description matches the parent view
另外,需要注意的是你必须设置
container.viewContext.automaticallyMergesChangesFromParent = true
container.viewContext.mergePolicy = NSMergePolicy.mergeByPropertyStoreTrump
为了让主上下文显示保存privateContext 后所做的更改。我把它放在 PersistenceController init loadPersistentStores 闭包之后。