Reputation: 175
I am creating a fitness journal app, and I store workout values in realm this this:
I am sorting the workouts using date. I want to accomplish something new, where I can have different weight and reps each set on the same exercise. It is based on this design:
I think the database has to bee something like this, but not sure:
- 23.11.2019
- Barbell Bench Press
- Set 1
- KG: 90
- Reps: 5
- Set 2
- KG: 87,5
- Reps: 6
- Triceps Pushdown
- Set 1
- KG: 110
- Reps: 6
- Set 2
- KG: 110
- Reps: 6
- Set 3
- KG: 112,5
- Reps: 5
Any tips on how I can do this?
Edit;
This is my current Workout.swift
class (not sure how to edit it to get what I want):
import Foundation
import RealmSwift
class Workout: Object {
@objc dynamic var date: Date?
@objc dynamic var name: String?
@objc dynamic var exercise: String?
@objc dynamic var sets = 0
@objc dynamic var reps = 0
@objc dynamic var kg: Double = 0.0
@objc dynamic var notes: String?
}
Upvotes: 0
Views: 294
Reputation: 1630
You would need to have three objects (Workout, Exercise, and Set) and have 2 many-to-many relationship as outlined in the documentation: https://realm.io/docs/swift/latest/#many-to-many
class Workout: Object {
@objc dynamic var date: Date?
// List of exercises (to-many relationship)
var exercises = List<Exercise>()
}
.
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")
}
.
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
}
}
EDIT
adding example code
let aSet0 = Set(numReps: 10, weight: 5.0, aNote: "light workout")
let aSet1 = Set(numReps: 10, weight: 20.0, aNote: "medium workout")
let aSet2 = Set(numReps: 10, weight: 30.0, aNote: "heavy workout")
let aWorkout = Workout()
aWorkout.name = example
aWorkout.sets.append(objectsIn: [aSet0, aSet1, aSet2] )
Another example code to display the sets for the "Bench Press" workout:
// Find the Workout instance "Bench Press"
let benchPressWorkout = realm.objects(Workout.self).filter("name = 'Bench Press'")
// Access the sets for that instance
let sets = benchPressWorkout.sets
// Access set[0]
let set0 = sets[0]
// Access reps and kg for set 0
let reps0 = set0.reps
let kg0 = set0.kg
// and so on ...
Upvotes: 2
Reputation:
Create a WorkOut this way
let realm = try! Realm()
var wo = WorkOut()//Do initialization for properties such as name,reps,...
try! realm.write{
realm.add(wo)
}
One record of WorkOut is written to your database
Upvotes: 0