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

3
我有一个实践应用程序的实体关系如下图所示。 entity relationship 我卡在了新食谱的保存部分,因为它由多个实体组成。
我使用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)

}

如果 (![context save:&error]) { NSLog(@"无法保存!%@ %@", error, [error localizedDescription]); } - NRV
在将所有值添加到对象中后调用此方法。 - NRV
在调用saveTapped()方法之前,Ingredient实体是否有一些值? - Abdullah
1个回答

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;

请注意,由于您已经为 "ingredient" 和 "recipe" 提供了反向关系,因此您不需要将 "newRecipeIngredient" 添加到 "newRecipe.ingredients" 中,也不需要将 "newRecipeIngredient" 添加到 "newIngredient.recipes" 中。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接