Ios NSPersistentStoreCoordinator-如何处理架构不兼容错误?
每次我更改应用程序的核心数据模型时,它都会在下一次启动时生成一个不可恢复的错误:“用于打开存储的模型与用于创建存储的模型不兼容” 我发现避免这种情况的唯一可靠方法是手动删除应用程序并让Xcode重新安装,或者使用其他技术手动删除核心数据存储区.sqlite存储区文件。这显然不适用于发送给用户 苹果用于初始化NSPersistentStoreCoordinator的默认应用程序代理模板包括以下注释:Ios NSPersistentStoreCoordinator-如何处理架构不兼容错误?,ios,core-data,core-data-migration,Ios,Core Data,Core Data Migration,每次我更改应用程序的核心数据模型时,它都会在下一次启动时生成一个不可恢复的错误:“用于打开存储的模型与用于创建存储的模型不兼容” 我发现避免这种情况的唯一可靠方法是手动删除应用程序并让Xcode重新安装,或者使用其他技术手动删除核心数据存储区.sqlite存储区文件。这显然不适用于发送给用户 苹果用于初始化NSPersistentStoreCoordinator的默认应用程序代理模板包括以下注释: __persistentStoreCoordinator = [[NSPersistentSto
__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];
*/
不过,我还没有找到任何关于如何“适当处理错误”的示例或说明
在这种情况下,我很乐意将数据库吹走,让应用程序根据在线数据重新生成数据库。这就是我手动清除数据库时所做的。但是我如何能够自动地响应这个错误条件呢
有什么好的例子可以解释最佳实践吗?最好的方法是使用轻量级迁移。请参阅Apple文档:
当您需要在新应用程序版本中更改模型时,您可以创建新模型。您可以在Xcode中执行此操作-只需选择当前模型,然后从菜单编辑器/添加模型版本中进行选择…如果没有此功能,自动迁移将无法工作。应用程序中的所有数据都是从在线源缓存的,因此我希望应用程序只检测到模型已更改,并将存储区一扫而光,而不是同时处理多个模型。我还没有看到一个好的例子来说明什么是做这件事的最佳实践。所以,这也是可能的。如果
[psc addPersistentStoreWithType:configuration:options:error
]失败,只需删除本地存储(sqlite文件),重新创建managedObjectModel并用新数据填充它(或从捆绑包中复制它)。我在我的应用程序中做了这个,从本地备份恢复损坏的数据库。