0

When a Core Data app is in early development, its Managed Object Model is often in constant flux. For each build, new Managed Objects and properties are added or deleted from the model.

When the Managed Object Model changes, the app will crash on next run with the error:

The model used to open the store is incompatible with the one used to create the store

The common advice in this situation is to delete the app from your device/simulator and re-run.

This works fine for developers using Xcode, but is annoying for non-technical stakeholders involved in the release process. It would be much preferable to not explain to the CEO or QA team that they must delete the app before installing that update from TestFlight. Or to field crashing bugs caused by this issue.

Once the models have been finalized a bit, we'll implement a real Core Data migration strategy.

In this dev phase, data loss is acceptable and expected.

This method will be removed before the app is released.

What's the easiest, lightweight, removable, debug way to "migrate" changes to the Managed Object Model between releases? This will likely be equivalent to "delete the app and re-run", but without needing to manually delete the app.

This should handle any and all changes to the Core Data stack, including adding and deleting Managed Objects and Properties.

Community
  • 1
  • 1
pkamb
  • 33,281
  • 23
  • 160
  • 191

2 Answers2

2

In this scenario, I would check compatibility against the current model and then delete the SQLite database if a migration would have been required.

Consider using (in Objective-C)

// error, sourceStoreURL, theManagedObjectModel are valid

NSDictionary *storeMetadata=[NSPersistentStoreCoordinator metadataForPersistentStoreOfType: NSSQLiteStoreType
    URL: sourceStoreURL error: &error];
BOOL storeIsCurrent=[theManagedObjectModel isConfiguration: nil
    compatibleWithStoreMetadata: storeMetadata];
if (!storeIsCurrent)
{
    // Alert user
    // Delete on-disk store via sourceStoreURL
    // (including -wal and -shm files if journaling enabled)
}
DDP
  • 2,463
  • 1
  • 26
  • 28
  • When doing this, make sure to delete the journal files in addition to the persistent store file-- i.e. the `-wal` and `-shm` files at the same location. Otherwise you might find that the old data didn't actually disappear. – Tom Harrington May 25 '16 at 17:39
  • Thank you @TomHarrington. I'll edit the answer to include this critical point. – DDP May 25 '16 at 18:07
1

You can change the store URL when you change the model.

You can also do model versioning even for early development and then delete them all before you ship. This can also help your team learn the ins and outs of model versioning.

Jon Rose
  • 8,373
  • 1
  • 30
  • 36