开发者

Duplicating (copying) a core data record and related records

开发者 https://www.devze.com 2023-02-20 02:06 出处:网络
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\"

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开发者_StackOverflow 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


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.


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];
}
0

精彩评论

暂无评论...
验证码 换一张
取 消