I get this error even with explicitly setting the relationship in my class. I have a workout class and an exercise class. workout is composed of an array of exercises:
@Model
class Workout: Identifiable {
var id: UUID
var name: String
var difficulty: Int
var workingTime: Int
var recoveryTime: Int
var count: Int
var duration: Int
var isSet: Bool
var setNumber: Int?
var restTime: Int?
// Define a one-to-many relationship with Exercise
@Relationship(deleteRule: .cascade, inverse: Exercise.workout) var exercises: [Exercise] = [Exercise]()
init(name: String, difficulty: Int, workingTime: Int, recoveryTime: Int, isSet: Bool, duration: Int, setNumber: Int? = nil, restTime: Int? = nil) {
self.id = UUID()
self.name = name
self.difficulty = difficulty
self.count = 0
self.duration = duration
self.workingTime = workingTime
self.recoveryTime = recoveryTime
self.isSet = isSet
self.setNumber = setNumber
self.restTime = restTime
}
}
@Model
class Exercise: Identifiable {
var id: UUID
var name: String
var imageName: String
var difficulty: Int
var guidelines: String
var muscle: String
// Define the relationship back to Workout
var workout: Workout?
init(name: String, imageName: String, difficulty: Int, guidelines: String, muscle: String, workout: Workout? = nil) {
self.id = UUID()
self.name = name
self.imageName = imageName
self.difficulty = difficulty
self.guidelines = guidelines
self.muscle = muscle
self.workout = workout
}
}
the error trigger when the user press the “save workout button”, defined like this, where exercises is an exercise array and workout a workout object:
private func saveWorkout() {
modelContext.insert(workout)
for exercise in exercises {
exercise.workout = workout
if var exerciseList = workout.exercises {
exerciseList.append(exercise)
workout.exercises = exerciseList
} else {
workout.exercises = [exercise]
}
modelContext.insert(exercise)
}
presentationMode.wrappedValue.dismiss()
showModal = false
}
I tried changing relationship parameters, allowing optionals exercise array, modifying order of the saveWorkout function, and changing my iOS target from 18 to 17.
Leandro is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.