这是我的Object
类的样子:
Workout.swift:
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
}
}
我正在尝试使用如下所示的buttonAction将其保存到领域:
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和reps值不同。保存后,将保存所有4组的最后一组/行。有提示吗?