且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

复制/备份持久存储

更新时间:2023-01-06 12:31:23

改变日志模式会消除日志文件,所以很简单.不过,我不知道我是否信任它供您使用——因为不能保证 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.