Question

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:

    • Close the persistent store and opening it again with @{@"journal_mode" : @"DELETE"} and then copy the .sqlite file.
  1. Add another persistent store and maybe copy from the original ps to the new one ?

Any better ideas ? Thank you.

Was it helpful?

Solution

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.

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. 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.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top