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
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
However, when I run this I get the following error: NSCFDictionary managedObjectContext]: unrecognized selector sent to instance
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