2011-12-17 96 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