核心数据手动迁移

我正尝试在我的项目中迁移到一个完全不同的新模型。 对于轻量级迁移而言,这些更改太多了,我认为最好的方法是遍历顶层对象,并自己设置所有的属性和关系。

如何将迁移过程设置为完全手动的? 我已经看着NSMigrationManager似乎需要一个NSMappingModel。 我见过的唯一的示例和教程使用inferredMappingModelForSourceModel:destinationModel:error:我不能使用,因为它无法推断映射模型。

我在正确的道路上,如果是这样,我怎么能在代码中完全手动创build一个映射模型? 谢谢您的帮助。

如果您的模型更改是至less有一个源和目标实体级别映射(例如,您的旧模型中有一个Vehicle实体,现在您想要将该数据迁移到Car ),那么您可以使用自定义映射模型移民政策。

该过程相当简单,在Xcode中,尝试添加一个新的映射模型文件到您的项目中,select源模型版本和目标模型版本。 Xcode试图找出你的源和目标实体的属性之间的映射是聪明的。 如果无法执行,则只需将映射留空即可,您可以设置自己的映射。

如果您想在映射期间执行除简单赋值,消隐或设置属性的默认值以外的其他操作,请使用名为NSEntityMigrationPolicy 。 创build你自己的子类并实现这个方法来做自定义映射:

 - (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]; } 

您可以阅读更多关于如何在这里进行自定义迁移。

检查CDWrangler 。 它是一个开源的核心数据控制器,可以逐步处理轻量级和手动迁移。

创build映射模型后,您需要的任何自定义策略只需要执行此操作

 // 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]; }