【问题标题】:Core Data rename attribute "deleted"Core Data 重命名属性“已删除”
【发布时间】:2016-08-24 10:29:05
【问题描述】:

我正在使用映射模型迁移数据模型。

一个实体有一个名为 deleted 的属性不会迁移,因为 Core Data 采用 NSManagedObjectdeleted 属性而不是我的。

如何强制映射模型使用我的属性?

我可以在值表达式中使用什么?这是我现在使用的:

谢谢。

【问题讨论】:

标签: ios objective-c core-data core-data-migration


【解决方案1】:

不幸的是,您使用了保留字(我怀疑当时会产生警告)。

您最好的选择是进行轻量级迁移,并且该值将不会迁移。然后在迁移之后;迭代数据并手动更新每个对象的值。您只需要这样做一次,因为一旦迁移完成,旧的保留字属性就会消失。

【讨论】:

  • 谢谢,但是如果我在轻量级迁移期间丢失了值,如何更新该属性?
  • 您在不删除旧属性的情况下创建新属性,然后迁移。迁移后,迭代对象并从旧值设置新值。在将来的某个时候,您可以删除旧的、现在未使用的值。
【解决方案2】:

我找到了解决办法:

我实现了一个自定义 MigrationPolicy 如下:

- (BOOL)createDestinationInstancesForSourceInstance:(NSManagedObject *)sourceInstance
                                  entityMapping:(NSEntityMapping *)mapping
                                        manager:(NSMigrationManager *)manager
                                          error:(NSError *__autoreleasing *)error
{
    NSManagedObject *newObject = [NSEntityDescription insertNewObjectForEntityForName:[mapping destinationEntityName] inManagedObjectContext:[manager destinationContext]];

    // Add the old 'deleted' attribute to a renamed attribute
    [newObject setValue:[NSNumber numberWithBool:[((OldEntityModel *)sourceInstance) deleted]] forKey:@"newDeletedAttribute"];

    // Add all the other attributes
    [newObject setValue:[sourceInstance valueForKey:@"field1"] forKey:@"field1"];
    [newObject setValue:[sourceInstance valueForKey:@"field2"] forKey:@"field2"];

    // Add the relationships
    NSSet *relationshipAttribute = [[NSSet alloc] initWithArray:[manager destinationInstancesForEntityMappingNamed:@"OtherEntityToOtherEntity" sourceInstances:@[[sourceInstance valueForKey:@"relationshipAttribute"]]]];
    [newObject relationshipAttribute forKey:@"relationshipAttribute"];

    [manager associateSourceInstance:sourceInstance withDestinationInstance:newObject forEntityMapping:mapping];

    return YES;
}

sourceEntity 转换为旧模型版本允许访问在轻量级迁移或映射模型中无法访问的 deleted 属性。

【讨论】:

    猜你喜欢
    • 2013-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-11
    • 2012-03-07
    • 2011-12-08
    相关资源
    最近更新 更多