【发布时间】:2016-08-31 10:52:57
【问题描述】:
TL;DR EDIT with answer
正如韦恩完美回答的那样,这就是我现在获取信息的方式:
let ingredientsToRecipe = recipe.valueForKey("ingredientsToRecipe")! as! NSSet
for i in ingredientsToRecipe {
print(i.valueForKey("amount")!)
print(i.valueForKeyPath("ingredient.name")!)
}
原始问题
我在理解 CoreData 中中间表的使用方面存在很大问题。我搜索了 SO 的答案,发现了一些关于中间表和多对多关系的线程,但那些要么是 Objective-C,要么对我没有帮助。
现在我想添加一个包含一堆配料的新食谱。 比方说一个汉堡。汉堡包括
-
1个黄瓜,
-
1 个番茄,
-
1 肉,
-
2 个面包
(好吃...)
这是我迄今为止尝试过的:
// Core Data
let appDelegate =
UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext
let entity = NSEntityDescription.entityForName("Recipe",
inManagedObjectContext:managedContext)
// creating a new recipe with name and id
let recipe = NSManagedObject(entity: entity!,
insertIntoManagedObjectContext: managedContext)
recipe.setValue("Burger", forKey: "name")
recipe.setValue("B_001", forKey: "id")
现在我得到了 Array:[NSManagedObject] 的成分(就像汉堡一样创建)和 Dictionary 的成分 ID。这就是我试图将我的食谱与配料结合起来的方式(在中间表上)。
for i in selectedIngredients { // the ingredient array
let ingredientsToRecipe = NSEntityDescription.insertNewObjectForEntityForName("RecipeIngredient", inManagedObjectContext: managedContext)
ingredientsToRecipe.setValue(i, forKey: "ingredient")
ingredientsToRecipe.setValue(recipe, forKey: "recipe")
let quantity = Double(quantityDictionary[(i.valueForKey("id") as! String)]!) // the amount-to-ID dictionary
ingredientsToRecipe.setValue("\(quantity)", forKey: "quantity")
}
最后我只是简单地保存了所有内容:
do {
try managedContext.save()
print("Saved successfully")
self.dismissViewControllerAnimated(true, completion: nil)
} catch let error as NSError {
print("Could not save \(error), \(error.userInfo)")
}
以上所有这些都以某种方式起作用。但现在我正在努力获取有关我的食谱的信息。 我应该如何获取这个特定汉堡的西红柿数量?
类似的东西
recipe.valueForKey("RecipeIngredient").valueForKey("amount") 工作,但我不知道哪个量来自哪个成分。
我做错什么了吗?
我可以/应该做什么更好?
目标是创建一个包含成分的食谱,然后在表格中填充有关该食谱及其成分数量(以及成分本身)的信息。
感谢您的帮助!
【问题讨论】: