Relationship

Relationship is established between two or more entities to explain how they are mutually associated to each other. In fact, the relationships allow the managed object of a particular entity to maintain references to the managed objects of another entity (destinations). In Core Data, the relationships are defined in the same way as the attributes are defined. The relationships are assigned a name, that serves as the key value to set and retrieve the object(s) represented by the relationship.

Note

The relationships are added to the entities in the Xcode's data model editor in the same way attributes are added.

Types of relationships

The relationship can be of three types:

  • One to one relationship
  • One to many relationship
  • Many to many relationship

One to one relationship

This relationship means a row in one entity will be associated with exactly one row in the destination entity. In other words, a managed object can contain a pointer to a single managed object of a specific entity. For example, the relationship from a child entity to a parent entity is a one to one relationship as a child can have only one parent.

One to many relationship

In this relationship, a row in one entity will be associated with more than one row in the destination entity. That is, a managed object will be associated with multiple managed objects in this case. For example, the relationship from the Customer to the Product entity is of a one to many relationship as a customer can purchase several products.

A one to many relationship is represented by instances of NSSet, which is an unordered, immutable collection that is not editable, or by NSMutableSet, an unordered collection that is editable.

Many to many relationship

In this relationship, a row in one entity will be associated with more than one row in the destination entity and vice versa is also true. That is, a row in the destination entity can be associated with more than one row in the source entity. For example, the relationship from an Employee to the Project entity is of many to many type as several employees can work on one project and an employee can work on several projects simultaneously.

Note

To define a many to many relationship, we have to use two one to many relationships. The first one to many relationship is set from the first entity to the second entity. The second one to many relationship is set from the second entity to the first entity.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.135.203.86