iphonecore-dataattributesobject-model

Why Does CoreData crash when I add an Attribute?


Everytime I add a new Attribute to my CodeData object model I have to clear my database file out otherwise I get the following error:

2010-11-13 15:26:44.580 MyApp[67066:207] * Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '+entityForName: could not locate an NSManagedObjectModel for entity name 'myApp''

There must be a way of being able to add extra fields without losing the whole database.

What do I need to do to retain my data?


Solution

  • there is a way, and this way is called automatic lightweight migration. It needs a codechange and an extra step when changing your object model.

    For the code you have to add two options to the method where you initialize your persistent store coordinator. something like this:

    - (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
        if (persistentStoreCoordinator_ != nil) {
            return persistentStoreCoordinator_;
        }
        NSString *storePath = [AppDelegate_Shared coredataDatabasePath];
        NSURL *storeURL = [NSURL fileURLWithPath:storePath];
    
    // important part starts here
        NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
                                 [NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption, 
                                 [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, 
                                 nil];
        NSError *error = nil;
        persistentStoreCoordinator_ = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
        if (![persistentStoreCoordinator_ addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:options error:&error]) {
    // and ends here
    
            LogError(@"Unresolved error %@, %@", error, [error userInfo]);
            // Do something 
        }    
        return persistentStoreCoordinator_;
    }
    

    Now if you want to change your model, you have to create a model version before you do any changes.
    Select your datamodel, and go into the main menu Design -> Data Model -> Add Model Version. Your "old" model will be renamed and you make your changes in the current model, the one with the green mark.
    All the old models are kept and will be put into your application, so your app can perform the 'automatic lightweight migration' and upgrade the existing database to your new model.