我想同时加载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.'
但是,如果我删除与containerAppGroup
OR相关containerLocal
的所有代码,错误就会消失,一切正常。但在这种情况下,我无法在我的应用程序运行时访问这两个容器数据。