Changing CoreData Model : retro compatibility

2020-07-24 05:35发布

I've been hitting this problem with coredata and it's driving me nuts because it should be straight forwards

I'm currently working on the first release of this app, os obviously I keep tweeking the core data model here and there,

However each time change the core data model I need to uninstall the application and reinstall the new version.

This is passable while its just me, but once released I need to be able to change update the app without my users reinstalling.

What am I missing,

Is there some code I need to write to tell core data how to modify the existing persistant data to the new one ?

THanks for your help

Jason

2条回答
姐就是有狂的资本
2楼-- · 2020-07-24 06:00

You need to read up on Core Data versioning and migration. Here's a blog post that explains it well:

http://www.timisted.net/blog/archive/core-data-migration/

查看更多
疯言疯语
3楼-- · 2020-07-24 06:16

Core data model - migration - adding new attributes/fields to current data model - no RESET of simulator or app required

Steps:

1) Create Model version from editor - Give it any meaningful name like ModelVersion2

2) Go to that model version and make changes to your model.

3) Now go to YourProjectModel.xcdatamodeld and set current version to newly created version.

4) Add below code to place where you are creating persistent coordinator -

NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:

[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption, 

[NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];

and set options value as options for method -

[__persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]

In my case, it looks something like this:

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{

 if (__persistentStoreCoordinator != nil) {
    return__persistentStoreCoordinator;
 }

 NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:

 [NSNumber numberWithBool:YES],      NSMigratePersistentStoresAutomaticallyOption,

 [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];


 NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"LGDataModel.sqlite"];

  NSError *error = nil;
  __persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
  if (!   [__persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:options  error:&error])
 {
    NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
    abort();
  }

  return__persistentStoreCoordinator;
 }

Link: http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CoreDataVersioning/Articles/vmInitiating.html#//apple_ref/doc/uid/TP40004399-CH7-SW1

查看更多
登录 后发表回答