我正在为我的 iOS 应用程序构建一个共享扩展。我正在使用应用程序组在应用程序和扩展程序之间共享 CoreData。现在我可以在扩展中加载数据,但是当我尝试添加/保存到它时,应用程序崩溃并显示错误消息:Unresolved error Foundation._GenericObjCError.nilError, [:]
.
class CustomPersistentContainer: NSPersistentCloudKitContainer {
override open class func defaultDirectoryURL() -> URL {
var storeURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.com.gn.papyrus")
storeURL = storeURL?.appendingPathComponent("Papyrus.sqlite")
return storeURL!
}
}
struct PersistenceController {
let container: NSPersistentCloudKitContainer
init(inMemory: Bool = false) {
container = CustomPersistentContainer(name: "Papyrus")
if inMemory {
container.persistentStoreDescriptions.first!.url = URL(fileURLWithPath: "/dev/null")
}
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
container.viewContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
container.viewContext.automaticallyMergesChangesFromParent = true
}
}
保存数据....
private func addToRoot() {
let newItem = Node(context: viewContext)
newItem.text = sharedText
newItem.dateAdded = Date()
do {
try viewContext.save()
} catch {
let nsError = error as NSError
fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
}
}