如何获取与 coreData 中的记录相关的关系

How to fetch relationship related to record in coreData

我是 coredata 的新手,我想获取与记录相关的属性。我使用下面的代码插入一条记录。

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)")
    }

我的CoreData关系如下

然后我使用以下代码获取用户

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

我的问题是如何获取与当前人相关的地址

您不获取它们,而是通过 addresses 属性访问它们

let adresses = personTest.adresses