Vic320
Vic320

Reputation: 1105

Duplicating (copying) a core data record and related records

I am writing an app that allows the user to create a "questionnaire", then add questions to it. I am using core data to store the info. I have created a questionnaire entity and have a "one to many" relationship with question entities. My question is, if want to allow the user to duplicate (copy) an entire questionnaire, questions and all what's the best way to do that?

So to be clear:

I have:

Questionnaire record ---> Question 1 record - Question 2 record - Question 3 record

and I want the user to be able to duplicate this and end up with this:

Questionnaire record ---> Question 1 record - Question 2 record - Question 3 record

Questionnaire (copy) record ---> Question 1 record - Question 2 record - Question 3 record

Upvotes: 1

Views: 1189

Answers (2)

André Morujão
André Morujão

Reputation: 7143

You said you want to duplicate an entire questionnaire, so assuming what you want is actually something like this:

Questionnaire ---> Question 1 - Question 2 - Question 3

Questionnaire (copy) ---> Question 1 (copy) - Question 2 (copy) - Question 3 (copy)

Then what you need is a deep copy. You can write something based on this NSManagedObject category, assuming you set your relationship's ownership rules properly on your data model.

Upvotes: 1

Jason Coco
Jason Coco

Reputation: 78393

You just insert a new managed object and then set all its values to the same thing as the original object. If you're using a specialized subclass for your managed object, you could even write a simple helper method (example assumes managed object is named Questionnaire, change accordingly):

-(Questionnaire*)copyQuestionnaire
{
  NSManagedObjectContext* ctx = [self managedObjectContext];
  // Obviously use the correct entity name...
  Questionnaire* newCopy = [NSEntityDescription insertNewObjectForEntityForName:@"Questionnaire" inManagedObjectContext:ctx];
  // Now just copy your properties, for this example we'll assume
  // a simple relationship called 'questions'
  [newCopy setQuestions:[self questions]];

  // We return a retained copy since our method name starts
  // with 'copy'
  return [newCopy retain];
}

Upvotes: 1

Related Questions