2012-09-05 84 views
2

與Core Data合作的每個人都知道消息「用於打開商店的模型與用於創建商店的模型不兼容」。包含應用更新的核心數據更新模型?

然後我必須從模擬器中刪除我的應用程序,然後重新構建它。

我的問題是,如果我提交了一個應用程序V1.0,然後在1.1版核心數據中添加了一些實體,這是否意味着更新到1.1的用戶將其數據清理?

回答

1

就你而言,它聽起來像是對舊數據模型的簡單擴展。如果你真的添加了一些新的實體甚至新的類,那麼所謂的輕量級遷移是適合你的正確方法。

其實在這種情況下,你幾乎沒有任何事情要做,但創建你的第二個模型,除了你原來的模型。重要的是,你有兩種模式,那麼應用程序只會加載你的第一個版本,沒有任何問題,以及新版本。

不要忘記將您的新模型標記爲新模型!

嘗試在創建新模型時要小心,因爲刪除模型是一件非常麻煩的事情。

您的代碼將看起來非常類似:

-(NSManagedObjectContext *)managedObjectContext { 
     if (managedObjectContext != nil) { 
      return managedObjectContext; 
     } 
     NSPersistentStoreCoordinator *lC = [self persistentStoreCoordinator]; 
     if (lC != nil) { 
      managedObjectContext =[[NSManagedObjectContext alloc] init]; 
      [managedObjectContext setPersistentStoreCoordinator: lC]; 
     } 
     return managedObjectContext; 
    } 


- (NSPersistentStoreCoordinator *) persistentStoreCoordinator { 
    if (persistentStoreCoordinator != nil) { 
     return persistentStoreCoordinator; 
    } 
    persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel: [self managedObjectModel]]; 

    // Allow inferred migration from the original version of the application. 
    NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys: 
          [NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption, 
          [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil]; 
    NSURL *storeUrl = [NSURL fileURLWithPath: [[self applicationDocumentsDirectory] stringByAppendingPathComponent: @"DBName.sqlite"]]; 

    NSError *error = nil; 

    if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeUrl 
                 options:options error:&error]){ 
     NSLog(@"Unresolved error %@, %@", error, [error userInfo]); 


    } 
    return persistentStoreCoordinator; 
} 

- (NSManagedObjectModel *) managedObjectModel { 
    if (managedObjectModel != nil) { 
     return managedObjectModel; 
    } 
    managedObjectModel = [NSManagedObjectModel mergedModelFromBundles:nil]; 
    return managedObjectModel; 
}