我有一个实践应用程序的实体关系如下图所示。
我卡在了新食谱的保存部分,因为它由多个实体组成。
我使用RecipeIngredient中间(联合)实体的原因是需要存储每个菜谱中食材数量的附加属性。
以下是具体实现,显然缺少将数量值分配给每个新食材的步骤,因为我不确定是否需要初始化RecipeIngredient实体,即使我需要,我也不知道如何将它们粘合成一个食谱。
我使用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)
}