核心数据与中间表(Swift 2)的多对多关系

时间:2016-05-05 15:13:40

标签: ios swift core-data

TL; DR EDIT回答

正如Wain完美回答的那样,这就是我现在获取信息的方式:

let ingredientsToRecipe = recipe.valueForKey("ingredientsToRecipe")! as! NSSet
for i in ingredientsToRecipe {
  print(i.valueForKey("amount")!)
  print(i.valueForKeyPath("ingredient.name")!)
}

原始问题

我在理解CoreData中的中间表的使用方面遇到了很大的问题。我搜索了SO的答案,发现了一些关于中间表和多对多关系的线索,但那些Objective-C或者没有帮助我的那些。

我有以下设置(简化): image

现在我想添加一些含有大量成分的新食谱。 让我们说一个汉堡。汉堡包括

  • 1 cocumber,
  • 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成分的成分。这就是我试图将食谱与成分结合的方式(在中间表中)。

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")工作,但我不知道哪种成分来自哪种成分。 我做错了吗? 我能做什么/我应该做得更好?

目标是创建一个含有成分的配方,然后在表格中填写有关配方及其配料量(以及配料本身)的信息。

我感谢任何帮助!

2 个答案:

答案 0 :(得分:1)

中间对象的强大之处在于它需要您的多对多关系并将其分解为多个一对多关系。一对一的关系很容易导航。

因此,从您的Recipe开始,您可以获得一系列RecipeIngredients,每个人都可以获得valueForKey("amount")valueForKeyPath("ingredient.name")

答案 1 :(得分:1)

为了获得特定食谱的成分数量,您可以使用以下谓词在RecipeIngredient创建一个获取请求:

var request = NSFetchRequest(entityName: "RecipeIngredient")
let predicate = NSPredicate(format: "recipe.name = %@ AND ingredient.name = %@", "burger","tomato")
request.predicate = predicate

然后你只需从返回的RecipeIngredient实体获得数量值。

相关问题