如何更改 xcdatamodel 中的属性类型?

How to change attribute type in xcdatamodel?

我是一个被分配到巨大项目的新手。我发现了一个需要修复的小错误,但我不知道具体如何修复。

好的,就在这里。 Xcode 的核心数据模型中的 issueNumber 属性设置为 Integer 64。我需要将其更改为 String,以便修复错误,但是当我将属性类型从 Integer 64 更改为 String 时,我的应用程序崩溃并出现如下所示的巨大输出:

CoreData: error: -addPersistentStoreWithType:SQLite configuration:(null) URL:file:///Users/Apple/Library/Developer/CoreSimulator/Devices/67D17D00-2AF8-4BC4-ABB7-091C95D02F35/data/Containers/Data/Application/B94B1310-4A63-4F91-AE7B-5F625697B3E2/Library/iMagDocument.sqlite options:{ NSInferMappingModelAutomaticallyOption = 1; NSMigratePersistentStoresAutomaticallyOption = 1; NSSQLitePragmasOption = { synchronous = OFF; }; } ... returned error Error Domain=NSCocoaErrorDomain Code=134130 "The operation couldn’t be completed. (Cocoa error 134130.)" UserInfo=0x7f405ef0 {URL=file:///Users/Apple/Library/Developer/CoreSimulator/Devices/67D17D00-2AF8-4BC4-ABB7-091C95D02F35/data/Containers/Data/Application/B94B1310-4A63-4F91-AE7B-5F625697B3E2/Library/iMagDocument.sqlite, metadata={ NSPersistenceFrameworkVersion = 519; NSStoreModelVersionHashes = {

它一直在继续...这就是我所做的:我将数据模型中的类型从 Integer 64 更改为 String:

好的,我做错了什么?肯定有一些我明显遗漏的东西,所以每次我更改属性类型时应用程序都会崩溃。

这真是个复杂的问题。您不能简单地更改属性的数据类型。您看到的错误表示核心数据无法将您的数据迁移到新版本。

1) 创建新的模型版本并在那里设置新的数据类型。参见 https://developer.apple.com/library/ios/recipes/xcode_help-core_data_modeling_tool/Articles/creating_new_version.html

2) 设置要使用的新模型版本。 https://developer.apple.com/library/ios/recipes/xcode_help-core_data_modeling_tool/Articles/setting_current_version.html

3) 您必须使用选项 NSMigratePersistentStoresAutomaticallyOption 和 NSInferMappingModelAutomaticallyOption 添加持久存储。

NSDictionary *options = @{NSMigratePersistentStoresAutomaticallyOption: [NSNumber numberWithBool:YES],
                          NSInferMappingModelAutomaticallyOption: [NSNumber numberWithBool:YES]
                          };

这是正确的方法:

- (NSDictionary *)persistentStoreOptions {
    return @{NSInferMappingModelAutomaticallyOption: @YES,
             NSMigratePersistentStoresAutomaticallyOption: @YES,
             NSSQLitePragmasOption: @{@"synchronous": @"OFF"}};
}