This week only. Pastebin PRO Accounts Christmas Special! Don't miss out!Want more features on Pastebin? Sign Up, it's FREE!
Guest

Copying NSManagedObjects Between NSManagedObjectContext Instances

By: a guest on Jun 8th, 2010  |  syntax: Objective C  |  size: 2.03 KB  |  views: 2,924  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. - (NSManagedObject*)copyObject:(NSManagedObject*)object
  2.                      toContext:(NSManagedObjectContext*)moc
  3.                         parent:(NSString*)parentEntity;
  4. {
  5.   NSString *entityName = [[object entity] name];
  6.  
  7.   NSManagedObject *newObject = [NSEntityDescription
  8.                                 insertNewObjectForEntityForName:entityName
  9.                                 inManagedObjectContext:moc];
  10.   [[self lookup] setObject:newObject forKey:[object objectID]];
  11.  
  12.   NSArray *attKeys = [[[object entity] attributesByName] allKeys];
  13.   NSDictionary *attributes = [object dictionaryWithValuesForKeys:attKeys];
  14.  
  15.   [newObject setValuesForKeysWithDictionary:attributes];
  16.  
  17.   id oldDestObject = nil;
  18.   id temp = nil;
  19.   NSDictionary *relationships = [[object entity] relationshipsByName];
  20.   for (NSString *key in [relationships allKeys]) {
  21.    
  22.     NSRelationshipDescription *desc = [relationships valueForKey:key];
  23.     NSString *destEntityName = [[desc destinationEntity] name];
  24.     if ([destEntityName isEqualToString:parentEntity]) continue;
  25.    
  26.     if ([desc isToMany]) {
  27.      
  28.       NSMutableSet *newDestSet = [NSMutableSet set];
  29.      
  30.       for (oldDestObject in [object valueForKey:key]) {
  31.         temp = [[self lookup] objectForKey:[oldDestObject objectID]];
  32.         if (!temp) {
  33.           temp = [self copyObject:oldDestObject
  34.                         toContext:moc
  35.                            parent:entityName];
  36.         }
  37.         [newDestSet addObject:temp];
  38.       }
  39.      
  40.       [newObject setValue:newDestSet forKey:key];
  41.      
  42.     } else {
  43.       oldDestObject = [object valueForKey:key];
  44.       if (!oldDestObject) continue;
  45.      
  46.       temp = [[self lookup] objectForKey:[oldDestObject objectID]];
  47.       if (!temp && ![destEntityName isEqualToString:parentEntity]) {
  48.         temp = [self copyObject:oldDestObject
  49.                       toContext:moc
  50.                          parent:entityName];
  51.       }
  52.      
  53.       [newObject setValue:temp forKey:key];
  54.     }
  55.   }
  56.  
  57.   return newObject;
  58. }
clone this paste RAW Paste Data