我正在开发一个iOS应用程序,该应用程序需要对实体的单个属性进行重迁移。在原始数据模型架构中,该属性的类型为Integer16,我需要在新架构中将类型更改为String。原始模型中存在的关系在新模型中将保持不变。

这是我第一次进行繁重的迁移,但幸运的是,这并不是一个非常复杂的迁移,但是不幸的是,我不确定如何进行迁移。我创建了一个MappingModel,然后又创建了一个NSEntityMigrationPolicy的子类,该子类从我创建的映射模型中引用。我意识到我需要重写此子类中的方法:createDestinationInstancesForSourceInstance,我尝试按以下步骤进行操作:

- (BOOL)createDestinationInstancesForSourceInstance:(NSManagedObject *)sInstance entityMapping:(NSEntityMapping *)mapping manager:(NSMigrationManager *)manager error:(NSError *__autoreleasing *)error {

    NSLog(@"boo");
    NSManagedObjectContext *destMOC = [manager destinationContext];
    NSString *destEntityName = [mapping destinationEntityName];
    NSString *name = [sInstance valueForKey:@"zip"];

    return YES;
}


运行我的项目后,应用程序中已经存在的属性值变为(null),这并不奇怪,上述输出在控制台中出现的次数与需要迁移的记录一样多。但是,现在如何将属性从Integer16转换为String?

最佳答案

这是createDestinationInstancesForSourceInstance的一些示例代码。基本上,您遍历属性并修改感兴趣的属性的值。不需要更改的属性将被简单地复制。

从旧值(int)到新值(string)的实际转换应放在here do conversion as needed的位置。

- (BOOL)createDestinationInstancesForSourceInstance:(NSManagedObject *)inSourceInstance
                                 entityMapping:(NSEntityMapping *)inMapping
      manager:(NSMigrationManager *)inManager
                                         error:(NSError **)outError {
    NSManagedObject *newObject;
    NSEntityDescription *sourceInstanceEntity = [inSourceInstance entity];

    // correct entity? just to be sure
    if ( [[sourceInstanceEntity name] isEqualToString:@"<-the_entity->"] ) {
        newObject = [NSEntityDescription insertNewObjectForEntityForName:@"<-the_entity->" inManagedObjectContext:[inManager destinationContext]];

        // obtain the attributes
        NSDictionary *keyValDict = [inSourceInstance committedValuesForKeys:nil];
        NSArray *allKeys = [[[inSourceInstance entity] attributesByName] allKeys];
        // loop over the attributes
        for (NSString *key  in allKeys) {
              // Get key and value
              id value = [keyValDict objectForKey:key];
              if ( [key isEqualToString:@"<-the_attribute->"] ) {
                 // === here retrieve old value ==
                 id oldValue = [keyValDict objectForKey:key];
                 // === here do conversion as needed ==
                 // === then store new value ==
                 [newObject setValue:@"<-the_converted_string->" forKey:key];
              } else { // no need to modify the value. Copy it across
                 [newObject setValue:value forKey:key];
              }
        }

    [inManager associateSourceInstance:inSourceInstance  withDestinationInstance:newObject forEntityMapping:inMapping];
    }
    return YES;
}

关于ios - 尝试对iOS中实体的单个属性进行核心数据迁移,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22262601/

10-14 22:31
查看更多