2014-09-10 75 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的格式,可以採用不同的方法來實現此目的。