【发布时间】:2020-12-12 20:16:31
【问题描述】:
我正在尝试使用NSPersistentCloudKitContainer 在 WatchOS 应用程序上设置 CoreData/CloudKit。但是,在调用container.loadPersistentStores 之后,viewContext.persistentStoreCoordinator 字段似乎仍然为零。
以下是一些代码示例:
Persistence.swift
struct PersistenceController {
static let shared = PersistenceController()
let container: NSPersistentCloudKitContainer
init() {
container = NSPersistentCloudKitContainer(name: "Test")
guard let description = container.persistentStoreDescriptions.first else {
fatalError("Could not retrieve a persistent store description.")
}
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
}
}
MainApp.swift
@main
struct EventLoggerApp: App {
let persistenceController = PersistenceController.shared
var body: some Scene {
WindowGroup {
ContentView()
.environment(\.managedObjectContext, persistenceController.container.viewContext)
}
}
}
ContentView.swift
struct ContentView: View {
@Environment(\.managedObjectContext) private var viewContext
func createRecord() {
print(viewContext.persistentStoreCoordinator) // this is nil
let sensorReadingDescription = NSEntityDescription.entity(forEntityName: "SensorReading", in: viewContext)! // this crashes
}
}
我遇到的错误是:
2020-12-12 11:56:32.205433-0800 EventLoggerWatch WatchKit Extension[400:541990] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '+entityForName: nil is not a legal NSPersistentStoreCoordinator for searching for entity name 'Test''
*** First throw call stack:
(0x1f4bb7dc 0x1edc9c04 0x23d68a44 0x174d34 0x174378 0x22fa9d6c 0x231422e0 0x23256ebc 0x22cb86a8 0x23256ed8 0x23256ebc 0x2327a6a4 0x2330f2dc 0x2324cdac 0x2324b6f4 0x2324b75c 0x2324bd20 0x4076df2c 0x40bd9f44 0x40763d70 0x40763e80 0x40763ce8 0x40b986cc 0x40b75abc 0x40becf04 0x40be59b4 0x1f43c4ec 0x1f43c3ec 0x1f43b74c 0x1f435dac 0x1f435574 0x235f94c0 0x40b580f8 0x40b5d5f8 0x350d9b68 0x1eed893c)
libc++abi.dylib: terminating with uncaught exception of type NSException
如果我可以提供更多有用的上下文,请告诉我,并提前感谢您的指导!
【问题讨论】:
-
loadPersistentStores是一种异步方法,虽然普通的基于磁盘的存储可能默认设置为shouldAddStoreAsynchronously = false,但我不会打赌NSPersistentCloudKitContainer会以同样的方式播放。用几张照片检查你的排序。 -
感谢沃伦的评论。我观察到
loadPersistentStorescompletionHandler中的打印没有出现。我可以在哪里传递shouldAddStoreAsynchronously标志? -
看起来
shouldAddStoreAsynchronously是NSPersistentStoreCoordinator对象上的一个标志,但据我所知,我并不是直接创建该对象。 developer.apple.com/documentation/coredata/… -
这是
NSPersistentStoreDescription上的一个属性,您可以恢复但在加载商店之前不要使用您可以更改该描述。 -
知道了!我刚刚尝试在
loadPersistentStores之前添加行description.shouldAddStoreAsynchronously = false,这导致了同样的错误。这符合你想要改变的想法吗?
标签: swift core-data swiftui cloudkit watchos