On one of my first trials with Core Data, I found that my program started crashing for no particular problem a couple of days after I'd start working with my particular data model. Looking at my log file I could see the crash, but not really what was causing it. This highlights one of the first problems with the Core Data: though it creates some default methods for setting up your managed object model, your managed object context, and your persistent store coordinator, it does no error management or reporting, instead somewhat unhelpfully offering the comment "Handle error".
Reporting Core Data Errors
So, if you're facing a mysterious Core Data error, that means that you probably should have filled in some error reporting in those places. It's easy enough to do, as the default templates set up NSError objects and fills them. All you have to do is, at the simplest level, report out the results to NSLog. Here's an example of "handling the error" in the Persistent Store Coordinator:
if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeUrl options:nil error:&error]) {
NSLog(@"Could Not Start Persistent Store: %@, %@", error, [error userInfo]);
}
You could do something similar in each other place marked as "handle error" in the standard Core Data templates. Once you've done that you'll then be able to extract errors from your "system.log" that will be more sensible than the crash you were seeing, but may still be somewhat confusing.
Solving the Incompatible Store Error
Here's the complete text of the error I got out of my crashing Core Data program once I reported the Core Data errors:
The model used to open the store is incompatible with the one used to create the store
You'll see this error if you've made a change to your data model (the creation of which was described in Core Data, part 2) without reinitiating your program from scratch afterward.
If you've been testing things on your iPhone or in the Simulator, this means you must totally delete the previous build of your program from your iPhone/Simulator, to get rid of the data that's hiding there in the Documents folder from your previous usage.
If you've prefilled a database (as I'll discuss in Core Data, part 4), you must redo that prefilling.
I find the fact that a program chokes rather than the data model updating itself rather unfriendly, and I'm not sure of the best way to resolve the issue if you've got a live app that you want to improve (though if you have ideas for that, please post them in the comments below). However if you're just running into an error because you're modifying your model as you develop a program, this article should tell you everything you need to know.
Next Up: Core Data reading and writing.
