iOS 8 Swift – 保存多个实体的数据
我的练习应用程序有以下实体关系。
而且我坚持一个由多个实体组成的新配方的保存部分。
我有RecipeIngredient中间(联合)实体的原因是,我需要一个额外的属性,将通过配方存储不同数量的成分。
这是明显错过了每个新成分的金额值的分配的实现,因为我不确定是否需要初始化这个RecipeIngredient实体,或者即使我做了,我也不知道如何将它们拼成一个整体食谱。
@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实体,或者即使我这样做,我也不知道如何将它们作为一个配方粘贴起来。
您将需要创buildRecipeIngredient实例(S),就像您对其他任何实体一样。 你可以做基本上相同的事情,你做了,例如食谱:
// 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;
请注意,由于您提供了ingredient
和recipe
反向关系,因此您无需将newRecipeIngredient
添加到newRecipe.ingredients
,也不需要将newRecipeIngredient
添加到newIngredient.recipes
。