开发者社区> 问答> 正文

将值从多个UITableView行保存到领域列表<>()

class Workout: Object {

    @objc dynamic var date: Date?
    // List of exercises (to-many relationship)
    var exercises = List<Exercise>()

}

Exercise.swift

class Exercise: Object {

    @objc dynamic var name: String?
    // List of sets (to-many relationship)
    var sets = List<Set>()
    var parentWorkout = LinkingObjects(fromType: Workout.self, property: "exercises")
}

Set.swift

class Set: Object {

    @objc dynamic var reps: Int = 0
    @objc dynamic var kg: Double = 0.0
    @objc dynamic var notes: String?
    // Define an inverse relationship to be able to access your parent workout for a particular set (if needed)
    var parentExercise = LinkingObjects(fromType: Exercise.self, property: "sets")

    convenience init(numReps: Int, weight: Double, aNote: String) {
       self.init()
       self.reps = numReps
       self.kg = weight
       self.notes = aNote
    }
}

我试图使用如下的按钮操作将其保存到领域:

let newWorkout = Workout()
let newExercise = Exercise()
let newSet = Set() 

let nowDate = Date()
func saveWorkout() {
    if numberOfSets > 0 {

        print("Saving workout...")

        let realm = try! Realm()

        let cells = self.tableView.visibleCells as! Array<ExerciseCreatorCell>

        for cell in cells {
            if cell.kgTextField.text == ""  {
                cell.kgTextField.shake()
                return
            } else if cell.repsTextField.text == "" {
                cell.repsTextField.shake()
                return
            } else { // Add every single set
                newSet.reps = Int(cell.repsTextField.text!)!
                newSet.kg = Double(cell.kgTextField.text!)!
                newExercise.sets.append(newSet)
            }
        }

        print("NEXT")
        newExercise.name = exerciseNameButton.currentTitle


        newWorkout.exercises.append(newExercise)
        newWorkout.date = nowDate

        try! realm.write {
            realm.add(newWorkout)
            print("Saved!")
        }
    } else {
        let alert = UIAlertController(title: nil, message: "Please add any exercise before saving!", preferredStyle: UIAlertController.Style.alert)
        alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil))
        self.present(alert, animated: true, completion: nil)
    }
}

中的每一行UITableView指示锻炼集。问题是,假设我总共添加了4组/行,kg的值和每组的代表值不同。保存后,它将保存所有4组的最后一组/行。有什么建议吗?

展开
收起
游客5akardh5cojhg 2019-12-05 16:33:18 415 0
0 条回答
写回答
取消 提交回答
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载