Defining relationships

A relationship in Core Data adds a reference to an Entity as a property on an Entity. In this case, you want to define a relationship between FamilyMember and Movie. The best way to describe this relationship is a one-to-many relationship. This means that every movie will have only one family member associated with it and every family member can have multiple favorite movies.

Configuring your data model with a one-to-many relationship from Movie to FamilyMember is not the most efficient way to define this relationship. A many-to-many relationship is likely a better fit because that would allow multiple family members to add the same movie instance as their favorite. A one-to-many relationship is used in this example to keep the setup simple and make it easy to follow along with the example.

Select the FamilyMember entity and click on the plus icon at the bottom of the Relationships list. Name the relationship movies and select Movie as the destination. Don't select an Inverse relationship yet because the other end of this relationship is not defined yet. The Inverse relationship will tell the model that Movie has a property that points back to the FamilyMember. Make sure that you select to many as the relationship type in the Data Model Inspector panel for the movies property. Also, select Cascade as the value for the delete rule:

The delete rule is a very important property to be set correctly. Not paying attention to this property could result in a lot of orphaned, and even corrupted, data in your database. For instance, setting this property to nullify simply sets the Inverse of the relationship to nil. This is the correct behavior when deleting a movie because deleting a movie shouldn't delete the entire family member who added this movie as their favorite. It should simply be removed from the list of favorites.

However, if a FamilyMember gets deleted and the relationship is nullified, you would end up with a bunch of movies that don't have a family member associated with them. In this application, these movies are worthless; they won't be used anymore because every movie only belongs to a single FamilyMember. For this app, it's desirable that when a FamilyMember gets deleted, Core Data also deletes their favorite movies. This is precisely what the cascade option does; it cascades the deletion over to the relationship's Inverse.

After setting the delete rule to cascade, select the Movie entity and define a relationship called familyMember. The destination should be FamilyMember and the Inverse for this relationship is favoriteMovies. After adding this relationship, the Inverse will be automatically set on the FamilyMember entity: