保存,删除和从一对多关系核心数据中获取数据

时间:2016-01-25 11:33:09

标签: swift core-data relationship one-to-many

我创建了一个类似的数据模型:

我有一个获取请求的代码:

func roundFetchRequest() -> NSFetchRequest {
    let fetchRequest = NSFetchRequest(entityName: "Customer")
    print("Check here: \(myRoundIndexPath)")
    //let predicate : NSPredicate = NSPredicate(format: "custRoundRel = %@", frc2.objectAtIndexPath(myRoundIndexPath!) as! RoundName) //ASSUME THIS IS CORRECT
    let sortDescriptor = NSSortDescriptor(key: "c2fna", ascending: true)
    //fetchRequest.predicate = predicate
    fetchRequest.sortDescriptors = [sortDescriptor]
    return fetchRequest
}

我注释掉的代码没有出错,但我似乎无法将客户保存到RoundName实例。当我使用其属性保存客户时,我使用了以下代码:

func newCust() {
    let cont = self.context
    let newCustomer = NSEntityDescription.entityForName("Customer", inManagedObjectContext: cont)
    let aCust = Customer(entity: newCustomer!, insertIntoManagedObjectContext: cont)

    aCust.c2fna = firstName.text
    aCust.c3lna = lastName.text
    aCust.c4tel = tel.text
    aCust.c5mob = mob.text
    aCust.c6ema = email.text
    aCust.c7hsn = houseNo.text
    aCust.c8fir = street.text
    aCust.c9sec = secondLine.text
    aCust.c10ar = area.text
    aCust.c11pc = postcode.text
    aCust.c12cos = cost.text
    aCust.c13fq = frequencyNumber.text
    aCust.c14fqt = frequencyType.text
    let DF = NSDateFormatter()
    aCust.c15das = DF.dateFromString(startDate.text!)
    //Do Pics in a minute & next date in a minute
    aCust.c17notes = notes.text

    //print("Desc = \(picRound.image?.description)")

    do {
        try context.save()
        print("Save Successful")
    } catch {
        print("Save Unsuccessful")
    }
}

将此客户与正确的回合链接起来的代码是什么?

谢谢,我对核心数据非常陌生,真的很感激任何帮助。

2 个答案:

答案 0 :(得分:1)

是的,您在获取请求中使用谓词,格式为

NSPredicate(format:"custRoundRel = %@", xxxx) 

其中xxxxRound个实例。

您也可以使用roundCustRel关系,具体取决于您对Customer实例的处理方式以及有多少关系。

答案 1 :(得分:-1)

您创建Customer个对象的方式与创建其他托管对象的方式相同。要将客户与正确的Round对象链接,只需设置一对一关系(Core Data将自动为您设置反向关系)。

newCustomer.round = round
// or, with your arcane attribute names
newCustomer.custRoundRel = theDesiredRoundObject

要获取一个特定回合的客户,您不需要获取请求或谓词。

round.customers
// or, with your arcane attribute names
round.roundCustRel