0

I am trying to copy a NSManagedObject that holds a core data instance, but I am being some very weird behaviours when doing so, its like the objects are somehow linked to each other after the copy and changes to one also affects the other.

NSManagedObject *originalTransactionRow = [self.transactionRowsRows objectAtIndex:indexPath.row];
NSManagedObject *originalTransactionHeader = [self.transactionRowsHeader objectAtIndex:0];
NSString *originalOrderNumberLocalStr = [originalTransactionRow valueForKey:@"orderNumber"];

NSString *returnOrderNumber = [NWTillHelper getNewOrderNumber];
NSManagedObject *returnOrderHeader = nil;
NSManagedObject *returnOrderRow = nil;

returnOrderHeader = [NSEntityDescription insertNewObjectForEntityForName:@"OrderHead" inManagedObjectContext:context];
returnOrderRow = [NSEntityDescription insertNewObjectForEntityForName:@"OrderRow" inManagedObjectContext:context];

returnOrderHeader = originalTransactionHeader;
returnOrderRow = originalTransactionRow;

NSError *error = nil;
if(![context save:&error]) {
   if([NWTillHelper isDebug] == 1) {
   NSLog(@"Can't Delete! %@ %@", error, [error localizedDescription]);
   return;
   }
}
Matt Douhan
  • 2,053
  • 1
  • 21
  • 40
  • A lot of experimentation on this subject can be found here: https://stackoverflow.com/questions/2730832/how-can-i-duplicate-or-copy-a-core-data-managed-object – danh May 31 '17 at 00:14

1 Answers1

2

If you're referring to these lines:

returnOrderHeader = originalTransactionHeader;
returnOrderRow = originalTransactionRow;

Those don't make copies. But it's not about Core Data or managed objects-- that's not how Objective-C works when you're detailing with object references. When you have a declaration like NSManagedObject *returnOrderHeader, the * means that you're saving a pointer to the object. Copying the pointer value doesn't copy the object data, it copies the pointer value. You end up with two variables with the same pointer, which means they're really the same object.

If you want to make a copy of an object, you need to take extra steps. If your object's class conforms to the NSCopying protocol then you can just call copy on the object. But managed objects don't do that, so you need to create a new instance and then write your own code to copy property values from the old instance to the new one.

Tom Harrington
  • 69,312
  • 10
  • 146
  • 170
  • got it that might explain the issues, so basically I need to create a new empty ManagedObject and then one by one set value based on the old object and save that new object to the context – Matt Douhan May 30 '17 at 23:00
  • That's right. Any relationships will also need to be re-created also. – Tom Harrington May 31 '17 at 03:08