"Routine" has a one-to-many relationship with "Workout". Both are of class NSManagedObject. I have an array of workouts called "myWorkouts" and I want to create a relationship between each workout in the array and the routine. Here is my data model:
Here is the code for the properties of the "Routine" class:
extension Routine {
@NSManaged var name: String?
@NSManaged var workout: Set<Workout>?
}
Here is the code where I'm trying to create the relationships:
var myWorkouts = [Workout]()
for workout in myWorkouts {
routine!.workout = Set(arrayLiteral: workout)
}
The problem I'm running in to is that every workout that is being saved overwrites the last work out saved, so, in reality, it's only saving the very last workout in the array as a relationship to routine. How do I save all of them?
You are overwriting the set of relationships each time through your loop:
for workout in myWorkouts { routine!.workout = Set(arrayLiteral: workout) }
This is equivalent to the following which overwrites the value stored in workout each time.
routine!.workout = Set(arrayLiteral: a)
routine!.workout = Set(arrayLiteral: b)
routine!.workout = Set(arrayLiteral: c)
Instead, you need to assign a Set that contains all workouts at once:
routine!.workout = Set(myWorkouts)