我正在尝试制作当前 Core Data 数据库文件的副本。
经过一些研究,我发现 migratePersistentStore(_:to:options:withType:)
在这种情况下可能很有用,因为 Apple documentation说,
This method is typically used for “Save As” operations.
虽然文档也说了,
Important
After invocation of this method, the specified store is removed from the coordinator thus store is no longer a useful reference.
因此,我尝试保留原始商店引用,以便该应用可以继续运行。
灵感来自 this thread ,我关注了Tom Harrington想法:
- Create a new migrate-only
NSPersistentStoreCoordinator
and add your original persistent store file.- Use this new PSC to migrate to a new file URL.
- Drop all reference to this new PSC, don't use it for anything else.
这是我的代码,用于使用 UIActivityViewController
共享备份 sqlite 文件:
func shareDatabase() {
let backupFileName = "Backup.sqlite"
let backupFilePath = URL(fileURLWithPath: NSHomeDirectory()).appendingPathComponent("Library").appendingPathComponent("Application Support").appendingPathComponent(backupFileName)
let mainDataPSC = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.persistentStoreCoordinator
let migratePSC = NSPersistentStoreCoordinator(managedObjectModel: mainDataPSC.managedObjectModel)
let origStore = mainDataPSC.persistentStores.first!
try! migratePSC.migratePersistentStore(origStore, to: backupFilePath, options: [NSSQLitePragmasOption: ["journal_mode": "DELETE"]], withType: NSSQLiteStoreType)
let activityVC = UIActivityViewController(activityItems: [backupFilePath], applicationActivities: nil)
present(activityVC, animated: true, completion: nil)
}
不幸的是,迁移后它仍然失去了对原始商店的引用,并且之后应用程序无法正常运行。
这是复制 sqlite 文件的正确方法吗? 如何保留原始引用?
谢谢大家!
最佳答案
你没有完全按照我在另一个答案中的意思去做,但公平地说,我可能没有像我应该的那样清楚地解释它。您遇到此问题是因为您仍在迁移 origStore
,所以它仍然被删除并且仍然变得无效。使用新的协调器是不够的——您必须确保不理会现有的核心数据堆栈。
更完整的过程描述是:
- 创建一个新的
NSPersistentStoreCoordinator
——您已经在这样做了。 - 使用
addPersistentStore(ofType:configurationName:at:options:)
将持久存储文件添加到协调器(您的migratePSC
)。此函数返回一个NSPersistentStore
对象。 - 使用新协调器 (
migratePSC
) 将新持久存储从第 2 步迁移到新位置 (backupFilePath
)。
在此之后,第 2 步中的持久存储将无效,但您不会在其他任何地方使用它,所以这无关紧要。同时,您现有的 NSPersistentContainer
及其所有属性都不会受到影响,您的应用程序会继续运行。
关于ios - 在核心数据中保存 sqlite 文件的副本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48404557/