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

时间:2018-10-23 19:35:26

标签: swift core-data relationship nsfetchrequest

我是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关系如下enter image description here

然后我用下面的代码

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

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

1 个答案:

答案 0 :(得分:1)

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

let adresses = personTest.adresses