Reputation: 10520
I have the following entity relationship for my practice app.
And I'm stuck with the saving part of a new recipe that consists of multiple entities.
The reason I have RecipeIngredient intermediate(joint) entity is that I need an additional attribute that will store a varying amount of an ingredient by recipe.
Here is the implementation which is obviously missing the assignment of the amount value to each new ingredient as I was not certain about the need for initialising this RecipeIngredient entity or even if I did, I wouldn't know how to glue them all up as one recipe.
@IBAction func saveTapped(sender: UIBarButtonItem) {
// Reference to our app delegate
let appDel: AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
// Reference moc
let context: NSManagedObjectContext = appDel.managedObjectContext!
let recipe = NSEntityDescription.entityForName("Recipe", inManagedObjectContext: context)
let ingredient = NSEntityDescription.entityForName("Ingredient", inManagedObjectContext: context)
// Create instance of data model and initialise
var newRecipe = Recipe(entity: recipe!, insertIntoManagedObjectContext: context)
var newIngredient = Ingredient(entity: ingredient!, insertIntoManagedObjectContext: context)
// Map properties
newRecipe.title = textFieldTitle.text
newIngredient.name = textViewIngredient.text
...
// Save Form
context.save(nil)
// Navigate back to root vc
self.navigationController?.popToRootViewControllerAnimated(true)
}
Upvotes: 3
Views: 1274
Reputation: 124997
I was not certain about the need for initialising this RecipeIngredient entity or even if I did, I wouldn't know how to glue them all up as one recipe.
You'll need to create the RecipeIngredient instance(s) just as you would for any other entity. You can do essentially the same thing that you've done e.g. for Recipe:
// instantiate RecipeIngredient
let recipeIngredient = NSEntityDescription.entityForName("RecipeIngredient", inManagedObjectContext: context)
let newRecipeIngredient = RecipeIngredient(entity:recipeIngredient!, insertIntoManagedObjectContext:context)
// set attributes
newRecipeIngredient.amount = 100
// set relationships
newRecipeIngredient.ingredient = newIngredient;
newRecipeIngredient.recipe = newRecipe;
Note that since you've provided inverse relationships for ingredient
and recipe
, you don't need to also add newRecipeIngredient
to newRecipe.ingredients
or add newRecipeIngredient
to newIngredient.recipes
.
Upvotes: 5