【问题标题】:Save a copy of sqlite file in Core Data在 Core Data 中保存 sqlite 文件的副本
【发布时间】:2018-07-02 10:34:09
【问题描述】:

我正在尝试制作当前 Core Data 数据库文件的副本。

经过一些研究,我发现migratePersistentStore(_:to:options:withType:) 在这种情况下可能有用,正如Apple documentation 所说,

此方法通常用于“另存为”操作。

虽然文档也说,

重要

调用此方法后,指定的存储将从协调器中删除,因此存储不再是有用的引用。

因此,我尝试保留原始商店引用,以便应用可以继续工作。

受到this thread的启发,我跟随Tom Harrington的想法:

  1. 创建一个新的 migrate-only NSPersistentStoreCoordinator 并添加您原来的持久性存储文件。
  2. 使用这个新的 PSC 迁移到新的文件 URL。
  3. 删除对这个新 PSC 的所有引用,不要将其用于其他任何事情。

这是我的代码,用于使用 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 文件的正确方法吗? 如何保留原始参考资料?

谢谢大家!

【问题讨论】:

    标签: ios swift sqlite core-data


    【解决方案1】:

    您并没有完全按照我在另一个答案中的意思做,但公平地说,我可能没有像我应该做的那样清楚地解释它。您遇到此问题是因为您仍在迁移 origStore,所以它仍然被删除并且仍然无效。使用新的协调器是不够的——您必须确保不理会现有的 Core Data 堆栈。

    对该过程的更完整描述是:

    1. 创建一个新的NSPersistentStoreCoordinator-- 你已经在这样做了。
    2. 使用addPersistentStore(ofType:configurationName:at:options:) 将您的持久存储文件添加到协调器(您的migratePSC)。该函数返回一个NSPersistentStore 对象。
    3. 使用新的协调器 (migratePSC) 将新的持久性存储从第 2 步迁移到新位置 (backupFilePath)。

    在此之后,第 2 步中的持久存储将无效,但您没有在其他任何地方使用它,所以这没关系。同时,您现有的NSPersistentContainer 及其所有属性都保持不变,您的应用程序继续工作。

    【讨论】:

    • 它有效。我使用let backupPersistentStore = try! migratePSC.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: mainDataPSC.persistentStores.first!.url!, options: nil) 添加了一个商店并将这个backupPersistentStore 迁移到backupFilePath。一切看起来都很实用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-03
    • 2021-12-31
    • 1970-01-01
    • 2011-09-28
    • 1970-01-01
    • 2015-07-16
    • 1970-01-01
    相关资源
    最近更新 更多