I did some searching around on this and all the examples are either obj-c or simply doesn't work in xcode 7 beta 6.
I have my xcode models set up like this:
So I have two entities, one called Person and one called Pet. Person has a name. Pet has a name and a type (dog, cat). Person has a to-many relationship to Pet and Pet has a to-one relationship to Person.
Here is my simple code:
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()
}
}
When I run it I get the following error:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unacceptable type of value for to-many relationship: property = "pet"; desired type = NSSet; given type = NSManagedObject; value = (entity: Pet; id: 0x7fa93bc2f4a0
pet.person = person
orpet.setValue(person, forKey:"person")
. Alternately change it to a one-to-one relationship. If it is many-to-many then you need to Add the pet to the relationship set. Something likeperson.pets.add(pet)
. I would advise the use of plural property descriptor for 'many' relationships to avoid confusion. – Duncan Groenewald