iOS 8 Swift - 保存多个实体的数据 [英] iOS 8 Swift - saving data of multiple entities
问题描述
我的练习应用程式有以下实体关系。
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.
我有RecipeIngredient中间(联合)实体的原因是我需要一个额外的属性,将通过食谱存储不同量的成分。
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.
这里是实现,显然缺少金额值分配每个新的成分,因为我不确定是否需要初始化这个RecipeIngredient实体,或者即使我这样做,我不知道如何粘合他们所有为一个食谱。
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)
}
推荐答案
需要初始化这个RecipeIngredient实体,或者即使我做了,我也不知道如何将它们全部粘合成一个配方。
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.
您将需要创建RecipeIngredient实例,就像对任何其他实体一样。你可以做基本上相同的事情,你曾经做过。
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;
请注意,由于您提供了成分
和 recipe
,您不需要也将 newRecipeIngredient
添加到 newRecipe。或或
添加
newRecipeIngredient
到 newIngredient.recipes
。
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
.
这篇关于iOS 8 Swift - 保存多个实体的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!