Search code examples
ioscore-datamany-to-many

Adding properties to many to many relationship?


I have been using Core Data to model my database. I have 2 entities that are in many to many relationship. Each person can have many addresses, and on each address multiple persons can live.

Now i would like to add property to this relationship. For example one person - address will have label home, other person - address can will have label mama's place.

I can't add this property on address entity, because same address will have different labels for different persons.

Since relationships are modeled like NSSets, I don't see a way to do what I want.

Can this be somehow done?


Solution

  • It is not possible to add attributes to a many-many relationship directly. The Apple-recommended approach (see "Modelling a relationship based on its semantics" in the CoreData Programming Guide) is to replace the many-many relationship with an intermediate entity, to which you add the attributes. Each of your existing entities will have a one-many relationship with the new entity.

    In your case, you might have something like this:

    Person     <--->> PersonAddressDetails <<--->    Address
    

    You can then add the label attribute to the PersonAddressDetails entity.