Swift 2.1核心数据 – 保存具有一对多关系的数据,但如果已经存在,则不要添加等值数据

我有一个ViewController创build一个新的配方数据。 要创build一个新的配方,用户需要填写标题,配料等,并select其类别。 为此,我build立了一对多关系的类别和食谱实体。

在创build函数中,我将需要进行以下search以查看类别实体是否已具有selectedCategory的值。

如果selectedCategory已经存在于Category实体中,我需要find它的索引并将该类别分配给Recipe实体,但是我不知道在这里需要写什么代码。

for category in categories { if category == selectedCategory { /* if selectedCategory already exists in Category entity, find its index and assign that category to Recipe entity.*/ } else { category.name = selectedCategory recipe.category = category } } context.insertObject(recipe) do { try context.save() } catch { print("Could not save recipe") } 

我创build了一个具有Core Data支持的单一视图应用程序。

我在数据模型中添加了两个实体:

CategoryEntity具有属性“name”。 RecipeEntity具有属性“标题”。

CategoryEntity与RecipeEntity之间有一个可选的,多对一的关系,称为“食谱”。 它有一个级联删除规则(如果您删除一个类别,所有相关的配方也会被删除)。

RecipeEntity与CategoryEntity具有必需的一对一关系,称为“类别”。

这些关系是相反的。

以下代码添加一个配方。 它首先获取或创build类别,并为其分配配方。

 import UIKit import CoreData class ViewController: UIViewController { @IBOutlet weak var category: UITextField! @IBOutlet weak var recipeTitle: UITextField! @IBAction func createRecipe(sender: AnyObject) { // Apple's out of the box Core Data app exposes a managedObjectContext on the appDelegate, so we'll use it here if let appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate { // we have to have a category name ... if let categoryName = category.text { // ... and a recipe title if let recipeTitle = recipeTitle.text { // get the category to associate this recipe with let categoryEntity = obtainCategoryEntity(categoryName, context: appDelegate.managedObjectContext) // create the recipe entity let recipeEntity = (NSEntityDescription.insertNewObjectForEntityForName("RecipeEntity", inManagedObjectContext: appDelegate.managedObjectContext) as! RecipeEntity) // assign the recipe to the category // note that you set up relationships in Core Data by assigning entities, // not indexes or id fields recipeEntity.category = categoryEntity // set the recipe's title recipeEntity.title = recipeTitle // save it! do { try appDelegate.managedObjectContext.save() NSLog("saved context") } catch let error as NSError { NSLog("failed to save context with error \(error)") } catch { fatalError() } } } } } func obtainCategoryEntity(name: String, context: NSManagedObjectContext) -> CategoryEntity { // this function gets or creates a category entity let fetchRequest = NSFetchRequest(entityName: "CategoryEntity") fetchRequest.predicate = NSPredicate(format: "name == %@", name) //find existing category, if it exists if let results = (try? context.executeFetchRequest(fetchRequest)) as? [CategoryEntity] { if results.count > 0 { // we really should only ever have one match, so return it return results[0] } } //category did not exist, so create it let categoryEntity = NSEntityDescription.insertNewObjectForEntityForName("CategoryEntity", inManagedObjectContext: context) as! CategoryEntity // set the category name categoryEntity.name = name // return it, but don't save it here - let the save later take care of it return categoryEntity } }