Martheli
Martheli

Reputation: 981

Core Data Swift 3 Relationship

I have two entities, Device and MDM. Device has two attributes, asset_tag and location. MDM has two attributes, asset_tag and os. I am trying to fetch asset_tag, os, and location for each asset_tag device. I had Xcode create my subclasses:

extension Device {

    @nonobjc public class func fetchRequest() -> NSFetchRequest<Device> {
        return NSFetchRequest<Device>(entityName: "Device")
    }

    @NSManaged public var asset_tag: String?
    @NSManaged public var location: String?
    @NSManaged public var devices: MDM?

}

extension MDM {

    @nonobjc public class func fetchRequest() -> NSFetchRequest<MDM> {
        return NSFetchRequest<MDM>(entityName: "MDM")
    }

    @NSManaged public var asset_tag: String?
    @NSManaged public var os: String?
    @NSManaged public var mdms: Device?

}

My fetch request is as follows:

var request = NSFetchRequest<NSFetchRequestResult>()
            request = Device.fetchRequest()
            request.returnsObjectsAsFaults = false
let results = try context.fetch(request) as! [Device]

Not sure how to get something like device.mdms.os to work to get the OS of a specific device.

Upvotes: 0

Views: 340

Answers (1)

Tom Harrington
Tom Harrington

Reputation: 70936

It looks like you have the names of your relationships backwards. Right now, Device has a relationship called devices of type MDM, and MDM has a relationship called mdms of type Device. That means you'd get the value of os for a Device with device.devices.os, which is probably not how you want to do it.

To fix it you probably want to reverse the names of those relationships-- in Device, change the name from devices to mdms, and in MDM, change the name from mdms to devices. In general the name of a relationship should describe the thing it relates to, not the thing that has the relationship.

Upvotes: 1

Related Questions