core-data - Swift 4 核心数据 - 获取关系

标签 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) 是否创建实体之间的关系?

最佳答案

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

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

关于core-data - Swift 4 核心数据 - 获取关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53647282/

相关文章:

objective-c - NRGridView 不会显示来 self 的核心数据数据库的数据

iphone - 核心数据 : NSCocoaErrorDomain=134040 Only Occurs On Real Phone, 不是模拟器

iOS 如何将文本字段中的数据保存在核心数据中并在表格 View 中显示这些数据?

node.js - 如何使用node-fetch通过discord webhook发送图像?

javascript - fetch post 调用后重定向

iphone - 选择核心数据

Swift 4 编程语言,inout 参数不适用于函数类型作为参数

ios - Swift Youtube 播放器内存泄漏

ios - 如何在 IOS swift 应用程序中启用堆栈粉碎保护?

javascript - Backbone : Collection Won't Reset