开发者

Why Does CoreData crash when I add an Attribute?

开发者 https://www.devze.com 2023-01-25 13:10 出处:网络
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:

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 d开发者_运维百科o I need to do to retain my data?


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.


In addition to @Matthias Bauch's answer

for Xcode 12.3

Choose from the main menu Editor -> Add Model Version

Why Does CoreData crash when I add an Attribute?

To add mark the New Model as the current model with a green checkmark Follow the below image

Why Does CoreData crash when I add an Attribute?

0

精彩评论

暂无评论...
验证码 换一张
取 消