首页 > 解决方案 > How to fetch relationship related to record in coreData

问题描述

I am Kind of new to coredata and I want to fetch the attributes related to a record. I use the following code to insert a record.

let entityDescription = NSEntityDescription.entity(forEntityName: "Person", in: mainContext!)
    let newPerson = NSManagedObject(entity: entityDescription!,insertInto: mainContext)
    let entityAddress = NSEntityDescription.entity(forEntityName: "Address", in: mainContext!)
    let newAddress = NSManagedObject(entity: entityAddress!,insertInto: mainContext)
    let otherAddress = NSManagedObject(entity: entityAddress!, insertInto:  mainContext)

    newPerson.setValue("Bart", forKey: "first")
    newPerson.setValue("Jacobs", forKey: "last")
    newPerson.setValue(44, forKey: "age")
    newAddress.setValue("Main Street", forKey: "street")
    newAddress.setValue("Boston", forKey: "city")
    newPerson.setValue(NSSet(object: newAddress), forKey: "addresses")

    otherAddress.setValue("5th Avenue", forKey:"street")
    otherAddress.setValue("New York", forKey:"city")
    // Add Address to Person
    let addresses = newPerson.mutableSetValue(forKey: "addresses")
    addresses.add(otherAddress)



    // Set First and Last Name


    do {
        try newPerson.managedObjectContext?.save()
    }
    catch
    {
        print("Couldnot do this op \(error)")
    }

My CoreData relations are as the following enter image description here

and I fetch the user with the following code

let fetchRequest = NSFetchRequest<NSFetchRequestResult>()

    let entityDescription = NSEntityDescription.entity(forEntityName: "Person", in: mainContext!)
    fetchRequest.entity = entityDescription
    fetchRequest.predicate = NSPredicate(value: true)
    do{
        let result = try self.mainContext?.fetch(fetchRequest)
        for personTest in result!
        {
            print(personTest)
        }
        if ((result?.count)! > 0)
        {
            let person = result![0] as! NSManagedObject
            print(person.value(forKey: "first"))
        }

    }
    catch
    {
        let fetchError = error as NSError
        print(fetchError)
    }

my question how can I fetch the addresses related to the current person

标签: swiftcore-datarelationshipnsfetchrequest

解决方案


You don't fetch them, you access them via the addresses attribute

let adresses = personTest.adresses

推荐阅读