0

在我使用 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 还有其他方法吗?

4

1 回答 1

1

您是对的,目前没有办法从 CoreStore 执行此操作。部分原因是真的没有办法安全地做到这一点。CoreStore 在移动它们之前无法知道在其他地方没有使用提到的文件。

对于 SQLite 存储,移动您提到的 3 个文件可能是最简单的实现。如果您对二进制属性使用“外部存储”,您还需要移动名为.<sqlitename>_SUPPORT. 所以如果你的 sqlite 文件被命名mydata.sqlite,这个文件夹就会被命名.mydata_SUPPORT

我的建议是为您的商店创建一个专用文件夹,并仅将与 SQLite 相关的文件放在那里。因此,下次您要移动目录时,只需移动文件夹本身即可。

于 2019-01-09T03:27:23.237 回答