2012-05-05 14 views
0

每當我更改我的應用程序的Core Data模型時,它會在下次啓動時生成一個不可恢復的錯誤:「用於打開商店的模型與用於創建商店的模型不兼容」。NSPersistentStoreCoordinator - 如何處理模式不兼容性錯誤?

避免這種情況的唯一可靠方法是找到手動刪除應用程序並讓Xcode重新安裝它,或者使用其他技術手動刪除Core Data存儲.sqlite存儲文件。這對於向用戶發貨顯然是不可行的。

蘋果的默認初始化NSPersistentStoreCoordinator應用代理模板中包含此評論:

__persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]]; 
if (![__persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) { 
    /* 
    TODO: Replace this implementation with code to handle the error appropriately. 

    ... 

    If you encounter schema incompatibility errors during development, you can reduce their frequency by: 
    * Simply deleting the existing store: 
    [[NSFileManager defaultManager] removeItemAtURL:storeURL error:nil] 

    * Performing automatic lightweight migration by passing the following dictionary as the options parameter: 
    [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption, [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil]; 

    */ 

我一直沒能找到有關如何「適當處理錯誤」,儘管任何樣品或指令。

我很樂意在這種情況下簡單地吹走數據庫,讓應用程序從在線數據中重新生成它。這是我手動將數據庫吹走時的操作。但是,我怎麼能自動響應這個錯誤條件呢?

有沒有解釋最佳實踐的好樣品?

回答

1

最好的方法是使用輕量級遷移。請參閱Apple文檔:http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CoreDataVersioning/Articles/vmLightweightMigration.html

當您需要在新應用程序版本中對模型進行更改時,您將創建新模型。您可以在Xcode中執行此操作 - 只需選擇您當前的模型並從菜單編輯器/添加模型版本中選擇...如果沒有此功能,自動遷移將無法工作。

+0

應用程序中的所有數據都通過在線來源緩存,因此我不希望應用程序檢測到模型已更改並將商店吹走。我還沒有看到一個很好的例子,但它被認爲是做這件事的最佳實踐。 – radven

+0

所以,這也是可能的。如果'[psc addPersistentStoreWithType:configuration:options:error']失敗,只需刪除本地存儲(sqlite文件)並重新創建managedObjectModel並用新數據填充它(或僅從bundle中複製它)。我已經在我的應用程序中從本地備份恢復損壞的數據庫。 –