gpt4 book ai didi

ios - NSPersistentStoreCoordinator - 如何处理架构不兼容错误?

转载 作者:行者123 更新时间:2023-11-29 04:40:32 27 4
gpt4 key购买 nike

每次我更改应用程序的核心数据模型时,它都会在下次启动时生成不可恢复的错误:“用于打开商店的模型与用于创建商店的模型不兼容”。

我发现避免这种情况的唯一可靠方法是手动删除应用程序并让 Xcode 重新安装它,或者使用其他技术手动清除 Core Data store .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];

*/

不过,我无法找到任何有关如何“适当处理错误”的示例或说明。

在这种情况下,我很乐意简单地删除数据库并让应用程序从在线数据重新生成它。这就是我手动清除数据库时所做的事情。但是我怎样才能自动响应此错误情况呢?

有什么好的示例可以解释最佳实践吗?

最佳答案

最好的方法是使用轻量级迁移。请参阅 Apple 文档:http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CoreDataVersioning/Articles/vmLightweightMigration.html .

当您需要在新的应用版本中对模型进行更改时,您可以创建新模型。您可以在 Xcode 中执行此操作 - 只需选择“您当前的模型”,然后从菜单“编辑器/添加模型版本”中选择...没有此操作,自动迁移将无法工作。

关于ios - NSPersistentStoreCoordinator - 如何处理架构不兼容错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10465879/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com