One of the biggest difficulties that I faced when learning how to use Coredata was dealing with one-to-many relationship. In every website or Stack Overflow’s question they only explain how to build the one-to-many relationship, but I couldn’t find about how to add a child object to its parent.
To start i created the the model in the .xcdatamodeld file.
Basically, I created 2 entities (Parent and Child) and a relationship in each one pointing the “Destination” to each other and the “Inverse” to the other’s relationship.
The Parent entity with it’s attributes and relationship.
As a parent can have many children, this is how the relationship is named. In the relationship’s inspector the type must be set as “To Many”.
The Child’s structure is similar the Parent.
Its relationship’s inspector will have the type set as “To One”.
After modeling the entities I ask Xcode to generate de model classes.
We have the Parent class:
And the Child class:
The class Parent has a var “children” of type NSSet and the class Child has a var “parent” of type “Parent”.
This is what it should look like.
That’s it… Just set the Child’s “parent” variable to the Parent object and Coredata does all the work.
To access each Parent’s child it’s only needed to iterate over the Parent’s children variable.
If you liked this post click here to share it on Twitter. Jaison Vieira jaisonv.com