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.name = [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?
Update 1: MOC setup like this:
- (NSManagedObjectContext *)insertionContext {
if (insertionContext == nil) {
insertionContext = [[NSManagedObjectContext alloc] init];
[insertionContext setPersistentStoreCoordinator:self.persistentStoreCoordinator];
}
return insertionContext;
}
Update 2:
The Data model has a to-Many relationship for recipe (object class: Recipe) to ingredients (object class: Ingredient). See:
If, instead of:
[recipe setIngredients:ingredientsSet];
I try and set the ingredients individually during the for loop - e.g. using:
recipe.ingredients = thisIngredient;
I get the error message: "warning: incompatible Objective-C types 'struct NSDictionary *', expected 'struct NSSet *' when passing argument 1 of 'setIngredients:' from distinct Objective-C type"