在我使用 CoreStore 5.3 的应用程序中,我试图将本地 sqlite 存储移动到另一个位置,以便能够从应用程序扩展访问数据库。虽然使用 FileManager.default.moveItem(at: oldURL, to: newURL) 移动当前 3 个文件(MyApp.sqlite、MyApp.sqlite-wal 和 MyApp.sqlite-shm)的文件工作正常,但我不认为它是这样做是个好主意...
if FileManager.default.fileExists(atPath: oldFileURL.path) {
do {
try FileManager.default.moveItem(at: oldFileURL, to: newFileURL)
try FileManager.default.moveItem(at: oldJournalingURL, to: journalingURL)
try FileManager.default.moveItem(at: oldSharedMemoryURL, to: sharedMemoryURL)
} catch let error {
// error handling ...
}
}
我知道 NSPersistentStoreCoordinator 上有 migratePersistentStore 的功能(https://developer.apple.com/documentation/coredata/nspersistentstorecoordinator/1468927-migratepersistentstore)
所以你通常会这样做,例如:
if let persistentStore = persistentStoreCoordinator.persistentStores.first {
do {
try persistentStoreCoordinator.migratePersistentStore(persistentStore, to: newFileURL, options: nil, withType: NSSQLiteStoreType)
} catch {
print("error")
}
}
...因为这也会移动所有关联的文件。
但是,显然这种方法没有在 CoreStore 中公开。除了作为 DataStack 的内部属性的 persistentStoreCoordinator 之外,访问它的唯一方法是通过 unsafeContext(),在 dataStack 已经设置之后,但这会导致更多麻烦,因为上下文会尝试执行 save() ,因为持久性存储已被移动,这将不起作用。
CoreStore 还有其他方法吗?