Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Importing old CoreData model into new project

I have an old Xcode project which contains a CoreData model (containing a version 1 and version 2 of the model). For several reasons I need to create a new Xcode project and transfer all of the code to the new project.

How can I import/transfer my old CoreData model in such a way that this new binary will still be able to read, and potentially migrate, the existing CoreData stores which are on my existing users' iPhones and iPads out in the world? I worry that if I push a new version using this new project that my users will update their app to the newest version and then it'll crash because the model or model version numbers don't match.

I'm NOT talking about adding a new version to the data model within the same app. I understand that process. This is about moving/importing/etc an existing data model from an old project into a new project.

Should I just copy the files over and add them to my project manually? Do I need to change things in my build settings to account for it?

like image 833
Kenny Wyland Avatar asked Mar 17 '12 04:03

Kenny Wyland


2 Answers

In the end, this is how I solved it:

  1. Create new project with CoreData
  2. Copy the raw CoreData model file over into my new project. Add it to the project.
  3. Delete the empty CoreData model autocreated by the new project.
  4. In the Project Settings, under Build Phases, Compile Sources, I added the copied CoreData model file.

Then I used the code that Scott provided above:

[NSManagedObjectModel mergedModelFromBundles:nil]

which automatically finds all of the models and combines them. By deleting the auto-generated one and adding my transferred one then everything works out just fine.

like image 139
Kenny Wyland Avatar answered Oct 23 '22 12:10

Kenny Wyland


As long as you keep the same application identifier, your new code will replace the binary for installed users while keeping all their data there untouched. So your new project essentially swaps in as a new binary. After that, it's up to you to make sure you load the right .sqlite file, handle the upgrades, etc.

Let me edit this a bit further. Downvote has a sad.

There is a ZMETADATA table (or equivalent, can't get to that now) that has all the information necessary to identify things. Further there is hashes to know whether the current versions are present such that automatic migration can happen. Provided the hashes exist, and that you've loaded your model via [[NSManagedObjectModel alloc] initWithContentsOfURL:[NSURL fileURLWithPath:modelPath]] instead of [NSManagedObjectModel mergedModelFromBundles:nil], then all should be well.

like image 27
Scott Corscadden Avatar answered Oct 23 '22 10:10

Scott Corscadden