I have a SwiftData model where a Workout has an array of Exercises and the Exercise Model has an array of Sets:
@Model
class Workout: Identifiable {
var id: UUID
var name: String?
@Relationship(deleteRule: .cascade) //when deleting a workout you delete all exericses that happened during that workout
var exercises: [Exercise]?
@Model
class Exercise: Identifiable {
var id: UUID
var exerciseName: ExerciseName
@Relationship(deleteRule: .cascade,inverse: Set.exercise) var sets: [Set]? //When an Exercise gets Deleted all Sets associated need to get deleted
var date: Date
@Model
class Set: Identifiable {
var id: UUID
var weight: Int
var reps: Int
var isCompleted: Bool
var exercise: Exercise
The way my add works when the user Navigates to addExercise view I create a local temporary Workout object that I will add to the modelContext when the user is done editing it. The user can then create an exercise here and it will appear in a list of exercise that will take the user to an Edit Exercise View:
Section(header: Text("Exercises")) {
if let exercises = workout.exercises {
ForEach(exercises){ exercise in
NavigationLink(value: exercise) {
Text(exercise.exerciseName.name)
.padding(.top, 5)
.padding(.bottom, 5)
}
}
.onDelete(perform: delete)
} else {
Text("No Exericses Yet")
}
}
.navigationDestination(for: Exercise.self) { exercise in
EditExeriseView(exercise: exercise, sets: exercise.sets ?? [])
.navigationBarBackButtonHidden(true)
}
In the Edit Exercise view I check if the passed Exercise has Sets and generate local temporary ones If it doesn’t, the user can then add Sets to this temporary set array. When the user clicks save the follow function is called:
func save() {
//first inserting the sets into the Sets model
for set in sets {
if(set.isCompleted){
modelContext.insert(set)
//xcode thinks i am trying to write to this actual exerises model context a set but im just rtying to add it to a local exercise object back in the AddworkoutView
exercise.sets?.append(set)
print("(exercise.sets!)")
print("(sets)")
} else {
print("this set was not toggled")
modelContext.delete(set)
}
}
//finished iterating through the sets and appending them so we can go back
dismiss()
}
I have confirmed this adds the set to the exercises sets array but the problem is I can only see the changes when I rerun the entire app. I have tried to manually add the sets to the passed exercise but Xcode thinks im trying to write it to SwiftData which is impossible because of the inverse relationship. Is there any way to see the changes without refreshing the app when the user navigates back to AddWorkoutView?