Swift 4核心数据-获取关系

时间:2018-12-06 08:25:12

标签: core-data swift4 fetch relationship

我有这样的实体:

Entity 1

Entity 2

我正在保存数据,

@IBAction func saveButton(_ sender: UIButton) {
    print("save")
    guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
        return
    }
    let context = appDelegate.persistentContainer.viewContext
    let workout = Workout(context: context)
    workout.name = workoutName.text
    workout.noOfSets = Int16(setsStepper.value)

    for index in 0..<setsVal {
        let sets = Sets(context: context)
        let test = IndexPath(row: index, section: 0)
        let cell = tableView.cellForRow(at: test) as! RepsTableViewCell
        sets.repAmount = Int16(cell.repsStepper.value)
        // Does this line not create the relationship between Workout and Set Entities?
        workout.addToSets(sets)
    }
    try! context.save()
}

我正在这样提取数据:

func fetch() {
    guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
        return
    }
    let context = appDelegate.persistentContainer.viewContext
    let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Workout")
    request.relationshipKeyPathsForPrefetching = ["Sets"]

    do {
        let result = try context.fetch(request)
        for data in result as! [NSManagedObject] {
            print(data.value(forKey: "name") as! String)
            print(data.value(forKey: "noOfSets") as! Int16)
        }
    }
    catch {
        print("failed")
    }
}

我已经将实体Workout和Sets之间的关系设置为一对多,但无法从Workout中检索Set的属性。

如何检索实体关系属性?

尽管已在xcdatamodel文件中设置了关系,但仍需要以编程方式指定该关系吗?

Workout.addToSets(sets)是否创建实体之间的关系?

1 个答案:

答案 0 :(得分:0)

您应该能够将您的关系实体作为属性访问,例如

for workout in result as! [Workout] {
    print(workout.name)
    if let sets = workout.sets { //assuming you have name your to-many relationship 'sets'
        print(sets.count)
    }
}