【发布时间】:2015-08-27 01:22:05
【问题描述】:
我对此进行了一些搜索,所有示例要么是 obj-c,要么在 xcode 7 beta 6 中根本不起作用。
我的 xcode 模型设置如下:
所以我有两个实体,一个叫做 Person,一个叫做 Pet。人有名字。宠物有名字和类型(狗、猫)。 Person 与 Pet 具有一对多关系,而 Pet 与 Person 具有一对一关系。
这是我的简单代码:
import UIKit
import CoreData
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let appDel: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let context: NSManagedObjectContext = appDel.managedObjectContext
let person = NSEntityDescription.insertNewObjectForEntityForName("Person", inManagedObjectContext: context)
let pet = NSEntityDescription.insertNewObjectForEntityForName("Pet", inManagedObjectContext: context)
person.setValue("Bill", forKey: "name")
pet.setValue("Ruff", forKey: "name")
pet.setValue("Dog", forKey: "type")
person.setValue(pet, forKey: "pet")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
当我运行它时,我收到以下错误:
由于未捕获的异常而终止应用程序 'NSInvalidArgumentException',原因:'不可接受的值类型 多对多关系:property = "pet";所需类型 = NSSet;给定 类型 = NSManagedObject;价值 = (实体:宠物;id:0x7fa93bc2f4a0
【问题讨论】:
-
您的宠物关系看起来可能是一对多的,在这种情况下,只需尝试像
pet.person = person或pet.setValue(person, forKey:"person")那样设置相反的关系。或者将其更改为一对一的关系。如果是多对多,则需要将宠物添加到关系集中。像person.pets.add(pet)这样的东西。我建议对“多”关系使用复数属性描述符以避免混淆。