0
votes

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:

enter image description here

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

2
Your pet relationship looks like it might be a one-to-many, in which case simply try setting the inverse like this pet.person = person or pet.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 like person.pets.add(pet). I would advise the use of plural property descriptor for 'many' relationships to avoid confusion.Duncan Groenewald

2 Answers

0
votes

In a one-to-many relationship, it is much more convenient to set the to-one relationship. To do it the other way round is possible, but more complicated, because you have to add one object to the possible NSSet of existing objects.

pet.person = person

(Using proper NSManagedObject subclasses.)

0
votes

Turned out I needed to create the class files. Once I created them everything started working properly.