Save many-to-one relationship from JSON into Core Data

Posted by Snow Crash on Stack Overflow See other posts from Stack Overflow or by Snow Crash
Published on 2010-06-03T13:42:19Z Indexed on 2010/06/03 13:44 UTC
Read the original article Hit count: 147

Filed under:
|

I'm wanting to save a Many-to-one relationship parsed from JSON into Core Data. The code that parses the JSON and does the insert into Core Data looks like this:

for (NSDictionary *thisRecipe in recipes) {  
  Recipe *recipe = [NSEntityDescription insertNewObjectForEntityForName:@"Recipe" inManagedObjectContext:insertionContext];
  recipe.title = [thisRecipe objectForKey:@"Title"];
  NSDictionary *ingredientsForRecipe = [thisRecipe objectForKey:@"Ingredients"];
  NSArray *ingredientsArray = [ingredientsForRecipe objectForKey:@"Results"];
  for (NSDictionary *thisIngredient in ingredientsArray) {
    Ingredient *ingredient = [NSEntityDescription insertNewObjectForEntityForName:@"Ingredient" inManagedObjectContext:insertionContext];
    ingredient.name = [thisIngredient objectForKey:@"Name"];
  }
}
NSSet *ingredientsSet = [NSSet ingredientsArray];
[recipe setIngredients:ingredientsSet];

Notes: "setIngredients" is a Core Data generated accessor method.
There is a many-to-one relationship between Ingredients and Recipe

  1. However, when I run this I get the following error: NSCFDictionary managedObjectContext]: unrecognized selector sent to instance

  2. If I remove the last line (i.e. [recipe setIngredients:ingredientsSet];) then, taking a peek at the SQLite database, I see the Recipe and Ingredients have been stored but no relationship has been created between Recipe and Ingredients

Any suggestions as to how to ensure the relationship is stored correctly?

© Stack Overflow or respective owner

Related posts about iphone

Related posts about core-data