开发者社区 问答 正文

将值从多个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 422 分享 版权
阿里云 AI 助理回答

在你的代码中,问题在于你只创建了一个Set实例(newSet),然后在循环中不断修改这个实例的属性并将其添加到Exercisesets列表中。由于每次循环都对同一个Set对象进行修改,最终列表中保存的是该对象的多个引用,它们都指向了最后一次修改的状态,因此看起来就像是所有集合都是最后一行的数据。

为了解决这个问题,你需要在循环内部为每一行创建一个新的Set实例。修改你的saveWorkout()函数如下:

func saveWorkout() {
    if numberOfSets > 0 {

        print("Saving workout...")

        let realm = try! Realm()

        let cells = self.tableView.visibleCells as! Array

        var exerciseSets: [Set] = [] // Create an array to hold the sets

        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
                let newSet = Set(numReps: Int(cell.repsTextField.text!)!, weight: Double(cell.kgTextField.text!)!, aNote: "") // Create a new set instance for each row
                exerciseSets.append(newSet) // Append the new set to the array
            }
        }

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

        // Now add all the sets to the exercise after the loop
        newExercise.sets.append(objectsIn: exerciseSets)

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

这样,每次迭代都会创建一个新的Set对象,并将这些不同的对象添加到exerciseSets数组中。最后,一次性将整个数组添加到Exercisesets属性中,确保每个集合都是独立且正确的。

有帮助
无帮助
AI 助理回答生成答案可能存在不准确,仅供参考
0 条回答
写回答
取消 提交回答
问答分类:
问答地址: