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组的最后一组/行。有什么建议吗?
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。