复制/备份持久存储 [英] Copy / Backup Persistent Store

查看:27
本文介绍了复制/备份持久存储的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常,当我为我的应用程序备份核心数据文件时,我只会在应用程序运行时将 .sqlite 文件复制到另一个位置.但是现在启用了日记 (wal),这不再起作用.我看不到 NSPersistentStoreCordinator 或 NSManagedObjectContext 写入新文件的方法.我猜我可能有两种方法:

Normally when I backed up the core data file for my app, I would just copy the .sqlite file to another location while the app was running. But now that journaling (wal) is enabled, this does not work anymore. I cannot see a way for NSPersistentStoreCordinator or NSManagedObjectContext to write a new file. I'm guessing maybe I have 2 methods:

    • 关闭持久存储并使用@{@"journal_mode" : @"DELETE"} 再次打开它,然后复制 .sqlite 文件.

有更好的想法吗?谢谢.

Any better ideas ? Thank you.

推荐答案

改变日志模式会消除日志文件,所以很简单.不过,我不知道我是否信任它供您使用——因为不能保证 Core Data 实际上已将所有新更改刷新到 SQLite 文件中.这可能没问题,但可能有一些 Core Data 尚未写出的内存更改.这几乎可以肯定是安全的,但偶尔也有可能无法正常工作.

Changing the journal mode will eliminate the journal files, so it's simple. I don't know that I'd trust it for your use, though-- because there's no guarantee that Core Data has actually flushed all new changes to the SQLite file. It might be OK, but there might be some in-memory changes that Core Data hasn't written out yet. This is almost certainly safe, but there's a small chance that it won't work right once in a while.

选项 2 会更安全,但需要做更多工作.我将使用 NSPersistentStoreCoordinatormigratePersistentStore:toURL:options:withType:error: 方法(文档特别提到它对另存为"有用)创建第二个持久存储"操作).告诉 Core Data 为您创建副本应该确保实际复制所有必要的内容.只是不要在您的主要持久存储协调器上执行此操作,因为在迁移之后,PSC 会删除对原始存储对象的引用(文件仍然存在,但该 PSC 不再使用它).步骤是

Option 2 would be safer, though more work. I'd create the second persistent store using NSPersistentStoreCoordinator's migratePersistentStore:toURL:options:withType:error: method (which the docs specifically mention as being useful for "save as" operations). Telling Core Data to create the copy for you should ensure that everything necessary is actually copied. Just don't do this on your main persistent store coordinator, because after migration, the PSC drops the reference to the original store object (the file's still there, but it's no longer used by that PSC). The steps would be

  1. 创建一个新的仅迁移 NSPersistentStoreCoordinator 并添加您的原始持久存储文件.
  2. 使用这个新的 PSC 迁移到新的文件 URL.
  3. 删除对这个新 PSC 的所有引用,不要将其用于其他任何用途.
  1. Create a new migrate-only NSPersistentStoreCoordinator and add your original persistent store file.
  2. Use this new PSC to migrate to a new file URL.
  3. Drop all reference to this new PSC, don't use it for anything else.

这篇关于复制/备份持久存储的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆