0
votes

Ive been stuck for a couple days, and need some help. My data model is setup with two entities(one to many relationship). Round <---->> Hole. In one view controller, I setup the Round and assign its properties(lets call this object roundObject). I do a fetch and grab this NSManagedObject roundObject and pass it on to a different View Controller. In this new VC, I want to now assign the properties of Hole(which has a relationship with Round). However, when I try to assign the relationship attribute of Hole( which is named holeToRound) it will not accept the NSManagedObject roundObject that I have passed in. It tells me that "NSManagedObject is not convertible to Round". So I tried casting MyRound as Round, and it then crashes the app telling me "Swift dynamic cast failed".

Any help would be great. Am I just missing a basic step in setting relationship properties? Essentially, I want to be able to set one entity properties in one VC, and the other entity via one-to-many relationship attributes in another VC. For instance, in this particular app, I have a single Golf Round where i define the Course name, and then I have MANY Hole objects (1-18) where I want to define and set the par and yardage for each hole.

Here is the two Model Classes

class Hole: NSManagedObject {

@NSManaged var par: String
@NSManaged var yards: String
@NSManaged var holeToRound: Round
@NSManaged var holeNum: String

}

class Round: NSManagedObject {

@NSManaged var course: String
@NSManaged var playerOne: String
@NSManaged var playerTwo: String
@NSManaged var roundToHole: NSSet

}

And this is the prepareFroSegue where I am trying to assign the relationship attribute

override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
    let appDel:AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
    let context:NSManagedObjectContext = appDel.managedObjectContext

    if segue.identifier == "hole1Segue" {



        let entity = NSEntityDescription.entityForName("Hole", inManagedObjectContext: context)

        let newHole = Hole(entity: entity, insertIntoManagedObjectContext: context)



        newHole.holeToRound = roundObject as Round

        context.save(nil)
}
2

2 Answers

2
votes

I have found that the reason why it would not allow me to assign my relationship properties is because i did not include the @objc() statement in my NSManagedObject model files. Once I did this, it worked just fine.

import Foundation
import CoreData

@objc(Round)
class Round: NSManagedObject {

@NSManaged var course: String
@NSManaged var playerOne: String
@NSManaged var playerTwo: String
@NSManaged var roundToHole: NSSet

}
1
votes

In Swift the error messages are often still quite misleading.

Have you tried creating the newHole with var rather than let?