Automatic Lightweight Migration

Heute mussten wir für ein App das Datenmodell der Datenbank ändern. Da das App bereits im App-Store ist, kann das aktuelle Datenmodell nicht einfach geändert werden. Deswegen haben wir eine Lösung gesucht, wie man ein Update auf ein neues Datenmodell machen kann und siehe da, die Lösung heisst “Automatic Leightweight Migration”.

Hier kann die Lösung eingesehen werden: http://stackoverflow.com/questions/1830079/iphone-core-data-automatic-lightweight-migration

Hier noch mal zusammengefasst:


To recap/Full guide:

1. Before making any change, create a new model version.

In Xcode 4: Select your .xcdatamodel -> Editor -> Add Model Version.
In Xcode 3: Design -> Data Model -> Add Model Version.
You will see that a new .xcdatamodel is created in your .xcdatamodeld folder (which is also created if you have none).

2. Save.

3. Select your new .xcdatamodel and make the change you wish to employ in accordance with the Lightweight Migration documentation.

4. Save.

5. Set the current/active schema to the newly created schema.

With the .xcdatamodeld folder selected:
In Xcode 4: Utilities sidebar -> File Inspector -> Versioned Core Data Model -> Select the new schema.
In Xcode 3: Design > Data Model > Set Current Version.
The green tick on the .xcdatamodel icon will move to the new schema.

6. Save.

7. Implement the necessary code to perform migration at runtime.

Where your NSPersistentStoreCoordinator is created (usually AppDelegate class), for the options parameter, replace nil with the following code:

[NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
[NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil]

8. Run your app. If there's no crash, you've probably successfully migrated :)

0. When you have successfully migrated, the migration code (step 7) can be removed. (It is up to the developer to determine when the users of a published app can be deemed to have migrated.)

IMPORTANT: Do not delete old model versions/schemas. Core Data needs the old version to migrate to the new version.

Posted in XCode

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>