views:

240

answers:

1

I need to make a duplicate of an existing object graph from one NSManagedObjectContext and insert it into a second NSManagedObjectContext.

Is there a straightforward way to do this? From what I can tell I could ask the MOC for its -registeredObjects and then do something like this to copy the attributes:

NSString* entityName       = [[sourceObject entity] name];
NSManagedObject* newObject = [NSEntityDescription insertNewObjectForEntityForName:entityName inManagedObjectContext:newMoc];
NSArray* attKeys            = [[[sourceObject entity] attributesByName] allKeys];
NSDictionary* attributes    = [sourceObject dictionaryWithValuesForKeys:attKeys];
[newObject setValuesForKeysWithDictionary:attributes];

However, I'm unsure how to copy the relationships across.

+3  A: 

I'd probably just save the managedObjectContext and reopen the persistent store in a new persistent store coordinator and grab the managed object context out of that. That should give you an object graph totally disjoint from your original.

Dave DeLong
Indeed, that sounds a lot easier than what I was messing with. I'll give it a try, thanks.
Rob Keniger
Works perfectly, many thanks.
Rob Keniger