Search code examples
iosswiftcore-dataentity-relationshipnsmanagedobject

Joining multiple relationships in swift


please help.

I have 3 NSManaged objects.

say Employee, Payslip, PayItem

Each Employee can have multiple Payslips, each Payslip can have multiple PayItems.

so the relationship is Employee <->> Payslip <<- PayItem

They are all set up as NSManagedOjects.

Then lets say I have 3 instances of each: (imagine I'm initialising each by adding this to the NSManagedObject class:

  convenience init(context: NSManagedObjectContext)
    {
    let entity = NSEntityDescription.entity(forEntityName: <entity>, in: context)!
    self.init(entity: entity, insertInto: context)'
    }

Then I can declare.

 var employee = Employee(context: context)
        var payslip = Payslip(context: context)
        var payItem = PayItem(context: context) 

I can then:

employee.addToPayslip(payslip) //Using the function created for me by default.

But if I try:

payslip.payItem = payItem

I always get the error:

Failed to call designated initializer on NSManagedObject class 'PayItem'

To summarise, I'm trying to link Employee to a payslip, that is one to many, then a payslip to a payitem, that is one to many. Why am I having such a tough time?


Solution

  • So it turned out I had a function that was returning an uninitialised version of PayItem. It took a while to track down, but zapping this resolved my problem.