1
votes

I want to know whats best practice when dealing with executing custom code after Core Data lightweight migration.

I'll try to explain what I mean, suppose I have 3 versions of my app:
ver 1.0.0 (core data model version is 1.0)
ver 1.1.0 (core data model version is 1.0)
ver 2.0.0 (core data model version is 2.0)

As you can see the core data model didn't changed between version 1.0.0 and 1.1.0, but it did changed between 1.1.0 and 2.0.0.

Now in addition to the model changes I need to run some custom code that updates some existing entities.
This custom code need to be executed if user just installed a newer version with with different model version, for example:
if user has version 1.0.0 and he is now installing version 2.0.0 - the code should be executed
if user has version 1.1.0 and he is now installing version 2.0.0 - the code should be executed

but on the other hand I dont want to run this code if the user installed a new version with same model version, or if user didn't have the app before, so there is no old data to update.
for example:
if user has version 1.0.0 and he is now installing version 1.1.0 - the code should NOT be executed
if user doesn't have the app and he is now installing version 2.0.0 - the code should NOT be executed

I search for this issue and found some questions talking about it:
Detecting a Lightweight Core Data Migration
Core Data : Post migration, additional migration code

but didn't find the right way for doing exactly what I wanted,
any help will be appreciated

1

1 Answers

1
votes

My suggestion is: create a pair key/value in NSUserDefault to save the version number. At startup of your application, it will do these works:

Step1: Verify if DB migration is necessary. If yes, execute your db migration process and wait until the end. You can find many solution of DB migration in stackoverflow. Step2: After DB Migration is done (or there is no migration to do): get the app version number (we call it _oldAppVersion) in NSUserDefault & defined in your application (in integrated version.h file for example) called _newAppVersion. Depend on values of the values of _oldAppVersion & _newAppVersion, you can decide to execute some codes. Step3: Update app version in NSUserDefaults with _newAppVersion if necessary.

You can exchange step1 & step2 to have your own implementation. All those 3 steps would be done under a splashscreen or a WAIT screen, before the first screen of your application is displayed.

The trick here is to duplicate your app's version somewhere in NSUserDefaults.

Hope that responds to your question.