2011-12-17 99 views
2

我刚刚创建了一个新版本的核心数据模型,其中包含一个额外的对象以及重新建立的关系。添加新版本的核心数据模型?

我现在有两个文件,Medical_Codes.xcdatamodelMedical_Codes_ 2.xcdatamodel

是否必须删除旧的NSManagedObject类文件并重新创建它们?

我必须更改持久性商店代码吗?

- (NSManagedObjectModel *)managedObjectModel 
{ 
    if (__managedObjectModel != nil) 
    { 
     return __managedObjectModel; 
    } 
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"Medical_Codes" withExtension:@"mom"]; 
    __managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL]; 
    return __managedObjectModel; 
} 

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator 
{ 
    if (__persistentStoreCoordinator != nil) 
    { 
     return __persistentStoreCoordinator; 
    } 

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

    NSFileManager *fileManager = [NSFileManager defaultManager]; 
    if (![fileManager fileExistsAtPath:[storeURL path]]) 
    { 
     NSString *defaultStorePath = [[NSBundle mainBundle] pathForResource:@"Medical_Codes" ofType:@"sqlite"]; 

     if (!defaultStorePath) 
     { 
      NSLog(@"Error: Could not locate Medical_Codes.sqlite in app bundle"); 
      return nil; 
     } 

     NSError *error = nil; 

     if (![fileManager copyItemAtPath:defaultStorePath toPath:[storeURL path] error:&error]) 
     { 
      NSLog(@"Error copying sqlite from bundle to documents directory: %@, %@", error, [error userInfo]); 
      return nil; 
     } 
    } 

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

    return __persistentStoreCoordinator; 
} 

回答

4

CoreData提供了不同级别的数据库旧架构到新架构的迁移。有时你可以进行轻量级迁移,这意味着除了创建新模型并生成新的托管对象类外,您不必做任何特别的事情。下一次启动应用程序时,模型管理器会发挥它的魔力并将您的旧数据迁移到新的模式。

但是,当您的新模型与旧模型显着不同时,您需要创建一个模型映射文件,为CoreData提供映射从旧到新的必要迁移信息。这个映射模型文件被Xcode拷贝到你的包中,模型管理器使用它来进行必要的迁移。

在运行时创建持久存储协调器期间,您还需要传递一些其他选项(因此,您必须稍微更改持久存储协调器代码)。有点像:

NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys: 
    [NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption, 
    [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, 
    nil]; 

if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeUrl options:options error:&error]) { 
    ... 
} 

所以,要回答你的第一个问题。如果您添加了新的属性或关系,那么您将需要创建新的托管对象文件。如果你所做的只是修改预先存在的属性或关系的一些选项,那么旧的托管对象文件仍然有效。

如果你还没有,你应该阅读苹果已经写了关于CoreData的一切。我还没有阅读关于这个主题的书,它比他们的在线文档更好。尤其请阅读versioning and migration上的信息。

+0

我不知道这是否对Jon有帮助,但这是我见过的最好的答案。它肯定帮我解决了我自己的移民问题。 – lukecampbell 2011-12-17 04:25:14