Reputation: 539
So i'm developing a workout tracker application and i have one entity which has all the exercises and another which will have saved workouts. I have setup a many-to-many relationship between the two as a workout can have many exercises and an exercise could have many workouts. I've subclassed my entities and i've been given these two variables...
// Workout Entity...
@NSManaged public var exercises: NSSet?
// Exercises Entity...
@NSManaged public var workouts: NSSet?
And i'm confused on how to write data to them. I have setup a tableview with all the exercises and when the user selects one it displays a checkmark. But i also want it to be saved to the relationships. So that when i query the data later on for a workout for example i want it to show me all the associated exercises on that workout. Any help would be greatly appreciated, thanks.
Upvotes: 0
Views: 132
Reputation: 19602
Assuming you have already created actual instances of your workout/exercise entities, Xcode generates methods to add and remove one or multiple related objects for you:
// MARK: Generated accessors for exercises
extension WorkoutEntity {
@objc(addExercisesObject:)
@NSManaged public func addToExercises(_ value: ManagedEmotionCategory)
@objc(removeExercisesObject:)
@NSManaged public func removeFromExercises(_ value: ManagedEmotionCategory)
@objc(addExercises:)
@NSManaged public func addToExercises(_ values: NSSet)
@objc(removeExercises:)
@NSManaged public func removeFromExercises(_ values: NSSet)
}
You can use them on you existing instances:
workoutInstance.addToExercises(exerciseInstance)
The inverse relationship is set by Core Data automatically, so:
exerciseInstance.workouts.contains(workoutInstance)
is now true
.
Upvotes: 0
Reputation: 39
Should be quite easy.
I guess you have a function which returns all selectes Workouts, i called it selectedExercises()
you just need to connect each exercise property with the workout property, and of course connect the workout property with each exercise
Something like that should do it for you:
let context = ...// your context
guard let workout = NSEntityDescription.insertNewObject(forEntityName: "Workout", into: context) as? Workout else {
fatalError()
}
let exercises = selectedExercises() //func returning an NSSet
let workoutsSet = NSSet(object: workout)
for exercise in exercises {
guard let exercise = exercise as? Exercise else { fatalError() }
exercise.workouts = workoutsSet
}
workout.exercises = exercises
do {
try context.save()
} catch {
fatalError()
}
Upvotes: 0