编辑完成后自动将单元格中的更改保存到对象?

Automatically saving changes in a cell to object when editing finishes?

我在我的项目中遇到了一场真正的噩梦,我需要为数组中的每个对象将单元格内容保存到一个对象中。我无法通过遍历 table 个单元格和数组对象并尝试将它们全部匹配来使它工作。

所以我的下一个想法是将 didFinishEditing 相关函数添加到 cellForRowAt 函数中?

我也不确定这是否有效,但这就是我所拥有的:

这里的每一行都有一个集合标签,一个可以滚动到数字的代表选择器,以及一个用于放置重量的文本字段。然后我将每一行保存为一个对象,用于存储集合、代表和权重。

问题是在编辑这个时,我怎样才能再次保存这些覆盖旧值?因此我上面的计划是使用 didFinishEditing 方法。

我之前的计划是下面的代码,但是我无法理解注释部分。所以我希望有人指导我在编辑时如何处理 saying 而不是这个不起作用的保存按钮功能!

    func saveUserExerciseSets() {

    if userExercise == nil {
        print("CREATING A FRESH SET OF SETS FOR THE NEW EXERCISE")
        for cell in self.customSetsTable.visibleCells as! Array<NewExerciseTableViewCell> {
            print("SAVING THESE CELLS \(customSetsTable.visibleCells)")
            let newUserExerciseSet = UserExerciseSet(context: self.managedObjectContext)

            newUserExerciseSet.setPosition = Int64(cell.setNumber.text!)!
            newUserExerciseSet.setReps = Int64(cell.repsPicker.selectedRow(inComponent: 0))
            newUserExerciseSet.parentExerciseName = self.userExerciseName.text

            if self.localeIdentifier == "en_GB" {
                let kgWeight = Measurement(value: Double(cell.userExerciseWeight.text!)!, unit: UnitMass.kilograms)
                newUserExerciseSet.setWeight = kgWeight as NSObject?
                newUserExerciseSet.initialMetricSystem = self.localeIdentifier

            } else if self.localeIdentifier == "en_US" {
                let lbsWeight = Measurement(value: Double(cell.userExerciseWeight.text!)!, unit: UnitMass.pounds)
                newUserExerciseSet.setWeight = lbsWeight as NSObject?
                newUserExerciseSet.initialMetricSystem = self.localeIdentifier
            }

            let fetchRequest: NSFetchRequest<UserExercise> = UserExercise.fetchRequest()
            fetchRequest.predicate = NSPredicate(format: "name == %@", self.exerciseNameToAddTo!)

            do {
                let parentExercise = try self.managedObjectContext.fetch(fetchRequest).first
                parentExercise?.addToExercisesets(newUserExerciseSet)
                print("SET ADDED TO EXERCISE")
            } catch {
                print("Fetching Routine Failed")
            }
        }

    } else if self.userExercise != nil {
        print("UPDATING EXISTING SETS FOR THE EXISTING EXERCISE")

        let cells = self.customSetsTable.visibleCells as! Array<NewExerciseTableViewCell>

        for cell in cells {
            let exerciseSets = self.userExercise?.exercisesets?.allObjects as! [UserExerciseSet]
            let sortedexerciseSets = exerciseSets.sorted { ([=10=].setPosition < .setPosition) }
            let cellsSet = sortedexerciseSets //match the sortedexerciseSets set object to the cell index positions

            cellsSet.setPosition = Int64(setsCell.setNumber.text!)!
            cellsSet.setReps = Int64(setsCell.repsPicker.selectedRow(inComponent: 0))

            if self.localeIdentifier == "en_GB" {
                let kgWeight = Measurement(value: Double(cell.userExerciseWeight.text!)!, unit: UnitMass.kilograms)
                cellsSet.setWeight = kgWeight as NSObject?
            } else if self.localeIdentifier == "en_US" {
                let lbsWeight = Measurement(value: Double(cell.userExerciseWeight.text!)!, unit: UnitMass.pounds)
                cellsSet.setWeight = lbsWeight as NSObject?
            }
            cellsSet.parentExerciseName = self.userExerciseName.text
        }
    }

    do {
        try self.managedObjectContext.save()
        print("THE SET HAS BEEN SAVED")
    } catch {
        fatalError("Failure to save context: \(error)")
    }
    delegate?.didFinishEditing()
    self.dismiss(animated: true, completion: nil)
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    guard let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as? NewExerciseTableViewCell
        else {
            fatalError("Unexpected Index Path")
    }

    cell.backgroundColor = UIColor.customBackgroundGraphite()
    cell.textLabel?.textColor = UIColor.white
    cell.repsPicker.dataSource = self
    cell.repsPicker.delegate = self
    configure(cell, at: indexPath)
    return cell
}

func configure(_ cell: NewExerciseTableViewCell, at indexPath: IndexPath) {

    // configuring cells when theres a loaded exercise causes the issues --------------------
    if self.userExercise != nil {
        print("RESTORING CELLS FOR THE EXISTING EXERCISE")
        let unsortedExerciseSets = self.userExercise?.exercisesets?.allObjects as! [UserExerciseSet]
        let exerciseSets = unsortedExerciseSets.sorted { ([=10=].setPosition < .setPosition) }

        let cellsSet = exerciseSets[indexPath.row]

        cell.setNumber.text = String((indexPath.row) + 1)

        let indexRow = Int(cellsSet.setReps)
        print("INDEX ROW INT IS \(indexRow)")

        cell.repsPicker.selectRow(indexRow, inComponent: 0, animated: true) //fix this crashing issue!

        let localeIdentifier = Locale(identifier: UserDefaults.standard.object(forKey: "locale") as! String)
        let setWeight = cellsSet.setWeight as! Measurement<UnitMass>
        let formatter = MassFormatter()
        formatter.numberFormatter.locale = localeIdentifier
        formatter.numberFormatter.maximumFractionDigits = 2

        if localeIdentifier.usesMetricSystem {
            let kgWeight = setWeight.converted(to: .kilograms)
            let finalKgWeight = formatter.string(fromValue: kgWeight.value, unit: .kilogram)
            let NumericKgResult = finalKgWeight.trimmingCharacters(in: CharacterSet(charactersIn: "0123456789.").inverted)
            cell.userExerciseWeight.text = NumericKgResult
        } else {
            let lbsWeight = setWeight.converted(to: .pounds)
            let finalLbWeight = formatter.string(fromValue: lbsWeight.value, unit: .pound)
            let NumericLbResult = finalLbWeight.trimmingCharacters(in: CharacterSet(charactersIn: "0123456789.").inverted)
            cell.userExerciseWeight.text = NumericLbResult
        }

    } else if self.userExercise == nil {
        print("NEW SET CELL ADDED FOR FRESH EXERCISE")
        cell.setNumber.text = String((indexPath.row) + 1)
    }
}

正确的方法是拥有这些集合的数组(我猜,因为你标记了核心数据,它们是 NSManagedObject 的实例?)。当用户在单元格中进行任何更改时(在文本字段中写入新值或滚动到代表的另一个值),您需要立即更新数组中的适当对象。然后,当您确定要保存更改时,您可以在 NSManagedObjectContext 上调用保存,或者只在上下文上调用回滚以取消所有更改。

尝试类似这样的操作来正确匹配 setId。这就是我认为的问题所在。

for x in sortedexerciseSets {

     if x.setPosition == Int64(setsCell.setNumber.text!)! {

       //save 
      }           
}