2014-09-10 76 views
0

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

我从我的webService接收MY_ENTITY类型的对象。

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

所以:

我OBJ_1在CoreData

我收到OBJ_2从WebService的。

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

回答

0

由于它们是两个单独的实例,因此您需要将所需的O2从O1移动到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服务将OBS作为JSON或XML获取,那么您可以使用它将JSON负载简单地推送到targetEntity中。这假设你的有效载荷attrs与你的实体attrs相一致。在这种情况下,你会与使用块或等效例如JSON有效载荷替换sourceEntity:

NSArray *seedData = [NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfFile:dataPath] 
                 options:kNilOptions 
                  error:&err]; 

    [seedData enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { 

... 
    id value = [obj objectForKey:attribute]; 
... 
} 
0

在哪种格式,您在从Web Service接收OBJ_2?

无论采用哪种方式,将OBJ_2分配给OBJ_1都不起作用,因为只会替换本地变量指向的引用。

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