The current app I'm working on as a side project is an expense tracking and budgeting app. For this app I am, of course, using Core Data to save all the tracked expenses that a user enters. Since I was modeling expense data, I gave it no additional thought to use a double-precision floating point as the type for the expense amount. It turns out, this isn't exactly such a hot idea.
Well, just re-define the Core Data property type from double to decimal and we're done, right? Well, sure. Except that I am making an effort to reduce user data loss and/or data corruption. So when this bad boy is live in the wild and storing user expense data, simply deleting all existing data and re-installing the new version of the app is not going to be an option. So I may as well practice migrating a versioned Core Data persistent store from one model version to another.
(In order to keep this post short and sweet, I will only reference Apple's documentation on Core Data Model Versioning and Data Migration. You should read it all if you are unfamiliar and want to get better at what you do.)
The first step is to create a new version of the data model in Xcode so that I could update the currency value properties from double to decimal type:
At this time I made the decision to not yet set the .xcdatamodeld document version to the newest model version so that if I ran the code on simulator or on a device before the migration code was all properly implemented I wouldn't corrupt any existing test data.
After the new model version has been made I added a new mapping model to the project, designating the source and destination version.
Next I had to create three different subclasses of NSEntityMigrationPolicy for each of my modeled entities that had currency attributes typed as double.
Once these classes were created, I opened my mapping model and for each entity mapping I entered the name of the custom NSEntityMigrationPolicy class created.
And that's that for the non-coding part of my custom migration. The next post will show the implementation of the migration code.
No comments:
Post a Comment