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.
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
speaks
relationship to Person
, and
destination
to Language
type
to To Many
spokenBy
relationship to Language
, and
destination
to Person
inverse
to speaks
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.