0

I have a core data model with two tables (meal and ingredients). I am trying to save ONE meal with MANY ingredients. I have the code below which loops through an array of ingredients. I'm trying to save it, but I cannot redeclare the "entity" below. How do I do it? I've tried releasing it, but that didn't work! Thanks for any help.

 for (x=0;x<ingredients;x++) {
  NSEntityDescription *entity = [NSEntityDescription insertNewObjectForEntityForName:@"Ingredient" inManagedObjectContext:managedObjectContext];
  entity.name = @"test";
 }

(this method does work saving ONE record out of the loop.. so that's not the problem)

1 Answer 1

3

You don't insert entities into contexts. You insert managed objects into contexts.

You should have something like:

NSManagedObject *myMO;
for (x=0;x<ingredients;x++) {
  myMo = [NSEntityDescription insertNewObjectForEntityForName:@"Ingredient" inManagedObjectContext:managedObjectContext];
  [myMO setValue:@"test" forKey:@"name"];
}

Of course, if have an NSManagedObject subclass you can just set the 'name' property directly.

The important thing is not confuse entities with instances of NSManagedObject or its subclasses. Entities are just descriptions of how objects relate to each other inside the object graph of the managed object context. The context uses the entity descriptions to figure out how all the actual instances fit relate to one another and how they are fetched and stored.

Sign up to request clarification or add additional context in comments.

1 Comment

thank you. worked a treat and a good explanation. Many thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.