Missing Mapping Model after editing the model

2019-08-29 19:55发布

问题:

I'm in the process of a manual core data migration and keep running into Cocoa Error 134140: NSMigrationMissingMappingModelError. I've noticed this happens any time I make any change to the model, even something as small as marking a property as optional. So far, the only solution I've found when this happens is to delete my mapping model and create a new mapping model. Are there any better, less tedious solutions?

回答1:

There's a menu option to resolve this. If you update your model anytime after creating your mapping model just do the following:

  1. Select the mapping model.
  2. Choose Editor -> Refresh Data Models.


回答2:

This happens because:

  • The migration map identifies the model files by the entity hashes, and
  • When you change an entity, you change its hash.

When you change the model, the map no longer matches it, and migration fails because no matching map can be found.

The workaround is to not mess with migration until you've nailed down what the new model looks like. Then create the map with the final version of the model. If you can't finalize the new model and need to work on migration, you've already discovered the necessary procedure.



回答3:

Tom is correct but I would take it one further. I would not do a manual/heavy migration, ever. If it cannot be done in a lightweight migration consider doing an export/import. It will be faster and more performant than a heavy migration.

My standard recommendation is to keep your changes small enough so that you can always do a lightweight migration.

Update on Import/Export

Heavyweight migration is a hold-over from OS X where memory was cheap. It should not be used in iOS. So what is the right answer?

My recommendation to people is to handle it on your own. Lightweight migration if at all possible, even if it requires walking through several models to get from A to B. However in your case that does not sound possible.

So the second option is export/import. It is very easy to export Core Data out to JSON. I even did a quick example in a Stack Overflow post about it.

First, you stand up the old model and the current store. This involves finding the right model version and manually loading it using [[NSManagedObjectModel alloc] initWithContentsofURL:] and pointing to the right model version. There are details on how to find the right mold version in my book (grin).

Then export the current model out to JSON. That should be fairly quick. However, don't do this in your -applicationDidFinish.. for obvious reasons.

Step two is to load up the new Core Data stack with the "current" model and import that JSON. Since that JSOn is in a known format you can import it fairly easily.

This will allow you to control the entire experience and avoid the issues that heavy migration has.