Moving Core Data Files

Using Core Data with an SQLite database and need to move the location of the store or replace the contents? Resist the temptation to use direct file operations and use the persistent store coordinator to do the job for you.

There are at least a couple of common situations when you may need to move a Core Data store:

You decided to add an App Extension and need to move your store into a shared AppGroup directory.

You need to populate or reset a store to a default database that you ship in the app bundle.

Avoid direct file operations

Moving the sqlite database with direct file operations is most likely not what you want:

There are two problems with this. Firstly you still need to tell the Core Data persistent store coordinator to use the new store location. Secondly it assumes that the persistent store is a single file.

Since iOS 7 Core Data uses an SQLite database with Write-Ahead Logging (WAL) journalling by default. In WAL mode Core Data appends transactions to a -wal file and uses a -shm shared memory file in the same location as the main sqlite file.

Moving just the sqlite file leaves you with potential data loss and an inconsistent store.

Persistent Store Migration

A better way that avoids both of these problems is to have the persistent store coordinator take care of the move.

Note if you are using the new in iOS 10 persistent container it maintains a reference to the persistent store coordinator: