Search code examples
iosswiftcore-datasetnsset

How to create a Core Data Relationship in Swift


I have two entities in my data model: Student <-->> Grade

In Objective-C I can use the following line to link the relationship of my two objects:

[newStudent setValue:[NSSet setWithObject:newGrade] forKey:@"grades"];

However in Swift, there is no NSSet. How do I perform the same thing?

newStudent.setValue(??????, forKey: "grades")

Solution

  • As already said, you can use NSSet to assign the to-many relationship.

    But it is actually easier to assign the inverse (to-one) relationship from Grade to Student:

    newGrade.setValue(newStudent, forKey: "student")
    

    This will automatically update the inverse relationship, i.e. add the newGrade object to the grades property of newStudent.

    And what you actually should do is to create NSMangedObject subclasses for your entities (in the "Xcode-> Edit" menu) and then use the property accessors:

    newGrade.student = newStudent
    

    This is easier to read, easier to write, you do not run the risk of typing errors in the key strings, and the compiler can perform a proper type checking.