user3353890 user3353890 - 7 months ago 8
Swift Question

Will CoreData duplicate objects?

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>?

}


enter image description here

Answer

So, you're working with Sets, which means that they only always contain each value once. Therefore, regardless of the enclosing objects (in this case NSManagedObjects), 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:

  1. If you haven't already, create the concrete subclasses using Xcode's built in tools, so you can directly access relationships and properties.
  2. In the concrete subclasses +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.
  3. In the future, just call routine.workout = workout, which is much clearer than the way your code defines setting the relationship.