每次我更改应用程序的Core Data模型时,它会在下次启动时生成不可恢复的错误:“用于打开商店的模型与用于创建商店的模型不兼容”。
避免这种情况的唯一可靠方法我发现是手动删除应用程序并让Xcode重新安装它,或使用其他技术手动吹走Core Data存储.sqlite存储文件。这对于向用户发货显然是不可行的。
Apple用于初始化NSPersistentStoreCoordinator的默认App Delegate模板包含以下注释:
__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];
*/
我找不到任何关于如何“恰当地处理错误”的样本或说明。
我很乐意在这种情况下简单地吹走数据库,让应用程序从在线数据中重新生成它。这是我手动吹掉数据库时的操作。但是,如何在响应此错误情况时自动执行此操作?
是否有任何好的样本解释最佳做法?
答案 0 :(得分:1)
最好的方法是使用轻量级迁移。请参阅Apple文档:http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CoreDataVersioning/Articles/vmLightweightMigration.html。
当您需要在新应用版本中对模型进行更改时,您需要创建新模型。您可以在Xcode中执行此操作 - 只需选择您当前的模型并从菜单中选择编辑器/添加模型版本......如果没有这个,自动迁移将无效。