【问题标题】:core data manual migration核心数据手动迁移
【发布时间】:2014-07-26 17:19:47
【问题描述】:
我正在尝试在我的项目中迁移到一个完全不同的新模型。对于轻量级迁移而言,这些更改太多了,我认为最好的方法是遍历顶级对象并自己设置所有属性和关系。
如何将迁移过程设置为像这样完全手动。我查看了似乎需要 NSMappingModel 的 NSMigrationManager。我见过的唯一示例和教程使用 inferredMappingModelForSourceModel:destinationModel:error:,我无法使用它,因为它无法推断映射模型。
我是否走在正确的道路上,如果是这样,我如何才能在代码中完全手动创建映射模型?感谢您的帮助。
【问题讨论】:
标签:
ios
core-data
core-data-migration
【解决方案1】:
如果您的模型更改使得您至少有一个源和目标实体级别映射(例如,您的旧模型中有一个 Vehicle 实体,现在您想将该数据迁移到 Car),那么您可以使用带有迁移策略的自定义映射模型。
该过程相当简单,在 Xcode 中,尝试将新的映射模型文件添加到您的项目中,选择源模型版本和目标模型版本。 Xcode 试图聪明地找出源实体和目标实体的属性之间的映射。如果不能,它会将映射留空,您可以设置自己的映射。
如果您想要在映射过程中执行简单分配、空白或设置属性默认值以外的操作,请使用称为NSEntityMigrationPolicy 的东西。创建您自己的子类并实现此方法来进行自定义映射:
- (BOOL)createDestinationInstancesForSourceInstance:(NSManagedObject *)instance
entityMapping:(NSEntityMapping *)mapping
manager:(NSMigrationManager *)manager
error:(NSError **)error {
NSArray *_properties = [mapping attributeMappings];
for (NSPropertyMapping *_property in _properties) {
if ([[_property name] isEqualToString:@"companyName"]) {
NSExpression *_expression = [NSExpression expressionForConstantValue:@"10to1"];
[_property setValueExpression:_expression];
}
}
return [super createDestinationInstancesForSourceInstance:instance
entityMapping:mapping
manager:manager
error:error];
}
您可以阅读有关如何进行自定义迁移的更多信息here。
【解决方案2】:
查看CDWrangler。它是一个开源的 Core Data 控制器,可以逐步处理轻量级和手动迁移。
在您创建映射模型以及您需要的任何自定义策略后,您只需执行此操作
// Migration
if ([[CDWrangler sharedWrangler] isMigrationNeeded]) {
// The key is the name of your starting model, and the value is the name of your mapping model. In this example they are Model.xcdatamodel and MappingModel.xcmappingmodel
[CDWrangler sharedWrangler].mappingsForModels = @{@"Model": @"MappingModel"};
[[CDWrangler sharedWrangler] migrate];
}