Reputation: 1891
I have an NSManagedObject called "Routine," that has already been saved to my data model. It has a to-many relationship to another NSManagedObject called "Workout". I want to edit the Routine in order to add more workout relationships to it to it.
let routine = fetchedResultsController.objectAtIndexPath(indexPath) as! Routine
The ViewController where I edit the Routine in my data model contains an array of Workout objects:
var myWorkouts = [Workout]()
Some of the workouts in the "myWorkouts" array may have been already associated with Routine, whereas others may not have (a new workout). I create a relationship between each workout and the routine like this:
for workout in myWorkouts {
routine!.setValue(NSSet(objects: workout), forKey: "workout")
}
My Question: If a relationship between a Routine and a Workout has already been created, will the above for-loop create a duplicate of that workout to associate with my routine, or will it only create new relationships for previously unassociated workouts?
I hope my questions makes sense. Thanks in advance for the help!
Routine CoreDataProperties File
import Foundation
import CoreData
extension Routine {
@NSManaged var name: String?
@NSManaged var workout: Set<Workout>?
}
Upvotes: 0
Views: 528
Reputation: 5188
So, you're working with Set
s, which means that they only always contain each value once. Therefore, regardless of the enclosing objects (in this case NSManagedObject
s), there will only be one in there. You're good - re-stating the relationship won't change anything.
I might suggest, however, that you can do a couple of things to make your life easier:
+NSManagedObjectProperties
file, redefine those to-many relationships from NSSets?
to Set<MyClass>?
. This allows you to call Swift-native functions, and works correctly, as Set
is bridged from NSSet
.routine.workout = workout
, which is much clearer than the way your code defines setting the relationship.Upvotes: 3