Search code examples
ioscore-datamany-to-manynsentitydescription

How to make a many to many relationship in core data in the .xcdatamodel


Hi guys really need help with the example below for core data - objective-C IOS

Entity1: Person Attribute: Name

Entity2: Languages Attribute: LanguageName

Example would be Name: John can speak LanguageName: English, Korean, Japanese

Example 2 would be LanguageName: Spanish, English, Korean is spoken by John, Amy, Ashley

First question is how do I make that relationship in the the xcdatamodel?

Second question is how to store that e.g. John speaks English, Korean, Japanese into the core data?

Third is how do I show that Data dynamically e.g

Say if I have a button that is generated by the languageName and when I click on it should display everyone who speaks that language in a tableview?

I have tried a different approach using bit shifting the and storing the sports in each bit and using a while loop to match it but I have been reading a while now and a many to many relationship seem to be more suitable.

Any help is appreciated, thanks in advance!

I didn't provide any code because I don't even know where to start.


Solution

  • To create a many-to-many relationship, you create two to-many relationships and make them the inverse of each other.

    In your case, you can

    1. Add a speaks relationship to Person, and
      • Set destination to Language
      • Set type to To Many
    2. Add a spokenBy relationship to Language, and
      • Set destination to Person
      • Set inverse to speaks
      • Set type to To Many

    By correctly setting the inverse, you can set the relationship from one side and Core Data will automatically take care of another side thus ensuring data consistency. For example, Mandy can speak English and Spanish. To save the languages she speaks into your Core Data store, simply do the following:

    // mandy, english and spanish are all NSManagedObject objects
    mandy.speaks = [NSSet setWithObjects:english, spanish, nil];
    NSLog(@"%@", [english.spokenBy containsObject:mandy] ? @"YES" : @"NO"); // YES
    

    You can listen to NSManagedObjectContextObjectsDidChangeNotification to get notified whenever your managed objects are changed (i.e., inserted, deleted or updated).


    Refer to this Apple Documentation for more info.