Save many-to-one relationship from JSON into Core Data
- by Snow Crash
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?