1

我想同时加载localNSPersistentContainer AppGroup的NSPersistentContainer

这是我所做的:

class MyAppGroupPersistentContainer: NSPersistentContainer{
    override class func defaultDirectoryURL() -> URL{
        return FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.com.myDomain.myApp")!
    }   
}
struct PersistenceController {
    static let shared = PersistenceController()
    
    let containerLocal: NSPersistentContainer
    let containerAppGroup: NSPersistentContainer

    init() {
        let a = NSPersistentContainer(name: "MyApp")
        a.loadPersistentStores(completionHandler: {(x, y) in})

        let b = MyAppGroupPersistentContainer(name: "MyApp")
        b.loadPersistentStores(completionHandler: {(x, y) in})

        self.containerLocal = a
        self.containerAppGroup = b
}

但是,如果我在单击 SwiftUI 按钮时执行此代码:

let allA = try! PersistenceController.shared.containerLocal.viewContext.fetch(GameData.fetchRequest())
let allB = try! PersistenceController.shared.containerAppGroup.viewContext.fetch(GameData.fetchRequest())
print(allA.count)
print(allB.count)

它崩溃了Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'executeFetchRequest:error: A fetch request must have an entity.'

但是,如果我删除与containerAppGroupOR相关containerLocal的所有代码,错误就会消失,一切正常。但在这种情况下,我无法在我的应用程序运行时访问这两个容器数据。

4

1 回答 1

0

您需要将 2 个商店加载到 1 个容器中。这是因为我们只能有一个 viewContext。有一些方法可以选择在查询或保存时使用哪些商店,请参阅affectedStores。您还可以使用模型编辑器中的配置来选择每个商店中的实体。

于 2022-02-23T08:39:34.243 回答