Bill
Bill

Reputation: 123

swift2 core data and working with relationships

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

Upvotes: 0

Views: 426

Answers (2)

Bill
Bill

Reputation: 123

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

Upvotes: 0

Mundi
Mundi

Reputation: 80273

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.)

Upvotes: 0

Related Questions