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

Posted

技术标签:

【中文标题】如何在coreData中获取与记​​录相关的关系【英文标题】:How to fetch relationship related to record in coreData 【发布时间】:2018-10-23 19:35:25 【问题描述】:

我是 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)
    

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

【问题讨论】:

【参考方案1】:

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

let adresses = personTest.adresses

【讨论】:

以上是关于如何在coreData中获取与记​​录相关的关系的主要内容,如果未能解决你的问题,请参考以下文章

如何使用CoreData获取相关实体的对象?

基于实体关系的核心数据获取

在 coredata 中获取关系对象

从 CoreData 关系中获取错误实体的对象

在 coreData 中获取一对多关系并放入 tableview

CoreData如何将项目添加到与实体相关的NSSet