iOS 8 Swift - 保存多个实体的数据

Seo*_*Lee 3 core-data ios 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)

}
Run Code Online (Sandbox Code Playgroud)

Cal*_*leb 5

我不确定是否需要初始化这个RecipeIngredient实体,或者即使我做了,我也不知道如何将它们作为一个配方粘合在一起.

您需要像创建任何其他实体一样创建RecipeIngredient实例.你可以做的基本上和你做的一样,例如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;
Run Code Online (Sandbox Code Playgroud)

请注意,由于您提供的逆关系ingredientrecipe,你不也需要添加newRecipeIngredientnewRecipe.ingredients或添加newRecipeIngredientnewIngredient.recipes.