views:

91

answers:

1

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)

+2  A: 

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.

TechZen
thank you. worked a treat and a good explanation. Many thanks
Matt Facer