编辑完成时自动将单元格中的更改保存到对象?
Posted
技术标签:
【中文标题】编辑完成时自动将单元格中的更改保存到对象?【英文标题】:Automatically saving changes in a cell to object when editing finishes? 【发布时间】:2017-03-26 21:28:26 【问题描述】:我对我的项目有一个真正的噩梦,我需要为数组中的每个对象将单元格内容保存到一个对象中。我无法通过循环遍历表格单元格和数组对象并尝试将它们全部匹配来使其工作。
所以我的下一个想法是在 cellForRowAt 函数中添加 didFinishEditing 相关函数?
我也不确定这是否可行,但这就是我所拥有的:
这里的每一行都有一个集合标签,一个可以滚动到数字的代表选择器,以及一个用于放置权重的文本字段。然后我将每一行保存为一个存储集合、代表和重量的对象。
问题是在编辑这个时,我怎样才能再次保存这些覆盖旧值?因此我上面的计划是使用 didFinishEditing 方法。
我之前的计划是下面的代码,但我无法弄清楚带注释的部分。所以我希望有人能指导我如何在编辑时说,而不是这个不起作用的保存按钮功能!
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 ($0.setPosition < $1.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 ($0.setPosition < $1.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)
【问题讨论】:
你能发布 cellForRow 方法吗?如何填充表格视图以确保单元格数据在不再可见时不会更改? 我已将 cellforRowAt 添加到 OP,通过调用 VC 时在 segue 中传递的实体关系填充 ots 【参考方案1】:尝试这样的方法来正确匹配 setId。这就是我认为的问题所在。
for x in sortedexerciseSets
if x.setPosition == Int64(setsCell.setNumber.text!)!
//save
【讨论】:
这解决了它与 OP 中的代码集成以使用我最初提出的方法!【参考方案2】:正确的方法是拥有这些集合的数组(我猜,因为你标记了核心数据,它们是 NSManagedObject 的实例?)。当用户在单元格中进行任何更改(在文本字段中写入新值或滚动到代表的另一个值)时,您需要立即更新数组中的适当对象。然后,当您确定要保存更改时,您可以在 NSManagedObjectContext 上调用 save,或者只需在上下文上调用 rollback 以取消所有更改。
【讨论】:
谢谢,是的,这是我在我的 OP 中写的关于我认为我应该做什么的内容,问题是如何实现它,我在哪里实现这个功能?因为我不能在 cellforrowat 中使用任何 didFinishEditing 命令,例如以上是关于编辑完成时自动将单元格中的更改保存到对象?的主要内容,如果未能解决你的问题,请参考以下文章
QAbstractTableModel 编辑而不清除单元格中的先前数据
将单元格中的 UITextField 文本保存到 NSUserDefaults 中?