Lapinou
Lapinou

Reputation: 1477

Migrating Core Data and Mapping Model

I hope all is fine for you :)

I have a database using Core Data. In my application V1.0, users can import some file in the apps. Now, for my V2.0, I would like to add a attribute in my model, but users who have the V1.0 and have some stored files have to hold all the files (no deleting if they upgrade the app...). So, I created a new Data Model with the new attribute, and set the current versioned core Data Model to my new Data Model... Ok. But if a launch my app, the file are deleted.

Normally, I have to use a Mapping Model. But how to do this ? Which is the source Data Model and destination Data Model when I'm creating the Mapping Model ?

Thank you so much for your help! Have a good day all! :)

EDIT:

If I add just a new attribute but not edit the names of attributes, maybe I don't need to create a Mapping Model... No ?

Upvotes: 3

Views: 2825

Answers (1)

James
James

Reputation: 131

If using a mapping model, your source model will be the v1.0 model and the destination will be your new v2.0 model. You may be able to get away without using a mapping model by using Lightweight Migration, documentation here.

The gist of what that says is that you'll need to go to your App Delegate and set the relevant options for the persistent store.

It should look something like

NSDictionary *options = @{NSMigratePersistentStoresAutomaticallyOption: @YES, NSInferMappingModelAutomaticallyOption: @YES};

[persistentStoreCoordinator addPersistentStoreWithType:storeType configuration:config URL:storeURL options:options error:&error];

The NSMigratePersistentStoresAutomaticallyOption key tells Core Data to check if the current managed object model version is different from the store you're using and to migrate the store to the updated model. The NSInferMappingModelAutomaticallyOption tells it to try to work the mapping out itself. This is the 'Lightweight Migration' bit.

Most of that will already be there, all you need to do is add the options dictionary. It will be in the - (NSPersistentStoreCoordinator *)persistentStoreCoordinator method. If you don't set at least the NSMigratePersistentStoresAutomaticallyOption then no migration will take place.

Lightweight mapping is also useful while developing. It means you can make changes to your model without needing to redo the mapping every time.

Upvotes: 5

Related Questions