【问题标题】:Update CoreData entity obj更新 CoreData 实体 obj
【发布时间】:2014-09-11 01:28:35
【问题描述】:

我有一个复杂的 CoreData 实体:MY_ENTITY

我从我的 webService 收到一个 MY_ENTITY 类型的对象。

在某些情况下,我需要使用收到的 obj 编辑本地 CoreData obj (MY_ENTITY)。

所以:

我在 CoreData 中有 OBJ_1

我从 WebService 收到 OBJ_2。

我需要从 OBJ_2 更新 OBJ_1。 我是要设置所有字段还是可以将 OBJ_1 ObjectID 分配给 OBJ_2 并保存上下文(相同的上下文)?

【问题讨论】:

    标签: objective-c core-data


    【解决方案1】:

    由于它们是两个独立的实例,因此您需要将所需的内容从 O2 转移到 O1。假设两个对象属于同一个实体类,您可以使用这样的例程逐个属性执行移动属性:

    // use entity description to get entity attributes and use as keys to get value
    
    // scan attributes
    NSDictionary *attributes = [[sourceEntity entity] attributesByName];
    for (NSString *attribute in attributes) {
        id value = [sourceEntity objectForKey:attribute];
        if (value == nil) {
            continue;
        }
    
       NSAttributeType attributeType = [[attributes objectForKey:attribute] attributeType];
    
       switch (attributeType) {
           case NSStringAttributeType:
               // value = [value stringValue];
               break;
           case NSInteger16AttributeType:
           case NSInteger32AttributeType:
           case NSInteger64AttributeType:
           case NSBooleanAttributeType:
               value = [NSNumber numberWithInteger:[value  integerValue]];
               break;
           case NSFloatAttributeType:
           case NSDecimalAttributeType:
               value = [NSNumber numberWithDouble:[value doubleValue]];
               break;
           case NSDateAttributeType:
               if (dateFormatter != nil)
                   value = [dateFormatter stringFromDate:value];
               break;
           default:
               value = @"";
               break;
       }
       [targetEntity setValue:value forKey:attribute];
    }
    

    注意,这只是一个示例,如果您打算使用,则需要对其进行清理并添加错误处理。此外,如果您通过 Web 服务以 JSON 或 XML 形式获取 O2,那么您可以使用它来简单地将 JSON 有效负载推送到 targetEntity。这假设您的有效负载属性与您的实体属性一致。在这种情况下,您可以使用块或等价物将 sourceEntity 替换为 JSON 有效负载:

       NSArray *seedData = [NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfFile:dataPath]
                                                            options:kNilOptions
                                                              error:&err];
    
       [seedData enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
    
    ...
       id value = [obj objectForKey:attribute];
    ...
    }
    

    【讨论】:

      【解决方案2】:

      您以哪种格式从 Web 服务接收 OBJ_2?

      无论哪种方式,将 OBJ_2 分配给 OBJ_1 都行不通,因为您只会替​​换局部变量指向的引用。

      要同步您的本地 CoreData 实体,您需要修改来自服务器的数据,修改现有实体的属性。根据您的数据模型和您接收 OBJ_2 的格式,有不同的方法可以实现这一点。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多