Translate

martes, 27 de marzo de 2012

Cambios del Data Model/ How to manage changes in the data model


Usually when you are creating you application you need to make a few changes to your data model. If you change the data model and try to run your application you would have a problem with the persistent store, because the file containing the data  does not match to the actual model data.
One way to solve this problem is to find the file in where the data are stored, and delete it. The problem is that you are going to loose the data stored on it.
The other way to solve it is to use model versioning, which is a feature provided by XCode to maintenance changes in our model data.

Model versioning allows us to made changes to the data model, and also migrate the data from old version to new version.

There are to types of migration, depending on the types of changes you made to your data model. These are automatic or lightweight migration and manual migration.

Here we are going to see how to made a lightweight migration for a small change in our model. In this case we need to add a new Attribute for an Entity.

1º Select the actual model data before you make any change on it. Choose Editor menu, and Add Model Version… then you must give a name for the new model version, and choose the model version from we are going to derive the  new model.



Then a new model data is created, and take notice that this new model is exactly to the one we have choose to derive from. In this new model we could made the changes we need. In this case add a new attribute.


2º Once we have created the new attribute, we need to generate the files .h and .m for the Entity changed.  Be careful to choose the new data model, click over the modified Entity, and then choose Editor on the menu, and Create NSManagedObject SubClass. Then a new version of the .h and .m will be created but with the same name as the old one, so a warning message about to replace the files will appear.



3º Now we are going to add new code for the place in where the persistent store coordinator is created:

NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
                  [NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
[NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];


The file must appear as follows:



This peace of code indicates that the migration process is going to be automatically.

4º Finally we are going to set our  new data model as de active one. In this case you must click over the root of the data model, and in the File inspector in the right panel go to Versioned Core Data Model, and choose the appropriate one.




And that´s all, you can run your application, but previously I recommend you to Clean and to Build it.





No hay comentarios: