How to make Deep Copy of NSManagedObject in Core Data
Asked Answered
H

1

6

I am trying to make a duplicate of an existing NSManagedObject and related sub-objects in Core Data. I can't seem to find an easy way to do this.

I have an NSArrayController that is populated from a Core Data database. I want to take the object at the selectionIndex and make a deep copy, keeping it related to the same parent object and copying all child objects.

Any assistance is appreciated!

Thanks to TechZen for the link. I used the sample code from that site and used this calling code:

RuleSetVersion *object = [[ruleSetVersionArrayController selectedObjects] lastObject];

NSString *parentEntity = @"RuleSet";

RuleSetVersion *newObject = (RuleSetVersion*)[self copyObject:object toContext:[self managedObjectContext] parent:parentEntity];

[newObject setRuleSetEffectiveDate:[[NSDate alloc] init]];
[newObject setRuleSetVersionLastModifiedDate:[[NSDate alloc] init]];

[newObject setRuleSet:object.ruleSet];

NSError *error;

if ([managedObjectContext save:&error] == NO) {
    [NSApp presentError:error];
}
Homes answered 26/9, 2010 at 22:0 Comment(0)
E
1

It's fairly involved. See this answer and the sample code linked from it:

How do I copy or move an NSManagedObject from one context to another?

Explication answered 27/9, 2010 at 22:40 Comment(2)
Thanks for the response! I see that answer, but it seems to discuss copying an object from one context to another. Does the same answer apply if I want to use only one context?Homes
It turns out that this works, but it took some re-jiggering of my calling code. The URL provides the code to perform the copy, but doesn't really address how to call it appropriately. I'm adding my code in my question above.Homes

© 2022 - 2024 — McMap. All rights reserved.