Core Data exceptions and errors

Recently I tried to learn more about Core Data and I must say it’s a fantastic framework and I almost instantly started to create practical data models / schemes and using them in my applications.

This post explains how to resolve some errors I encountered during my adventures with Core Data. At the beginning I started to play around with Xcode template with Core Data. I lunched project and everything worked fine. Then I tried to add attribute in model entity (“Event”) and change corresponding code in controllers. I lunched app and then appeared first error:

reason = "The model used to open the store is incompatible with the one used to create the store";

First search result in Google pointed me to Patric Proctor blog

That was easy. Remove app from simulator, run again and voila. Error occurs also when you add new entity or make any changes.

Next I decided to create new version of my data model. In order to do that I selected model file (.xcdatamodeId) and I choose from menu Editor -> Add Model Version… Xcode 4 nicely created new file with number 2, so I added new entity in my brand new model version file and also changed code to fetch and save new entities. To avoid previous error I removed old app from simulator, relaunched project and I got new error:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'executeFetchRequest:error: A fetch request must have an entity.'

So I checked my code for entity name misspelling and nothing. To resolve problem this time I read nice article about versioning form Apple: Core Data Model Versioning and Data Migration Programming Guide. It turned out that I forgot to set current model version to new one. In Xcode 3 to set current model version you choose: Design -> Data Model -> Set Current Version. In Xcode 4 after selection model file with versions, in Utilities view under Versioned Data Model select current version, and that’s it.

If you know any noteworthy Core Data errors, please share!

Happy coding!

EDIT: As my friend Lukasz pointed out solution for the first problem is only useful during development (and not always, especially when you don’t want to recreate imputed data every time you change data model). Imagine that you released your app and after some time you need to implement new features and maybe change data model. You can’t force users to delete and install app again. More sophisticated solution for this problem is data migration. You can learn more about data migration from Core Data Model Versioning and Data Migration Programming Guide

Be Sociable, Share!