Learn Courses My Dashboard

Coredata: many to many relation, how to link the 2 entity?

Hi I have 2 entities

  1. Words
  2. Tags

Words can have multiple tags and its true with tags, Tags can have multiple words


  1. If I add the tag to the word, do I still need to execute the reverse function of it, that is to add the word to tag? I am not sure if I executed 1, core data might automatically execute the reverse.

here is the portion of the code when I added the tag to word

rcvTags.forEach { tag in
            if let id = tags.firstIndex(where: {$0.name == tag.text}){
                // if tag is already existing, just add it to word
            } else {
                // if tag, not yet existing, create the tag
                let newTag = Tags(context: self.context)
                newTag.name = tag.text
                newTag.id = UUID()
                // add to the word
                newWord.addToWithTagsOf(newTag) //<---  Add tag to word
                isTagUpdated = true
        // save context

I think in the Tag entity part, there is also a generated function where I can add the word to tag

extension Tags {

    @NSManaged public func addToWithWordsOf(_ value: Words). // Add Word to Tag

//.... and so on

I was searching the net but I could not find any sample many to many Coredata codes/reference

Upon testing, and studying more. I guessed that the answer is “Yes”

There is no need to add the instance of the entity to the other side.
It is handled by the core data automatically.

I was also able to access the NSSet contents from the link below:

as example:

Button("Test") {
                    var tagsName = dB.tags[0].name
                    let wordFromTag : [Words] = dB.tags[0].withWordsOf?.allObjects as! [Words]
                    let WordItems = dB.words[7].withTagsOf?.allObjects as! [Tags]