How does Core Data use inverse relationship?

Core Data can make things easier for you, though. If the relationship weren’t
ordered, you’d just be able to set the one side of the relationship (e.g., walk.dog =
currentDog) rather than the many side and Core Data would use the inverse
relationship defined in the model editor to add the walk to the dog’s set of walks.

I did not understand this paragraph. First, what does it mean by “if relationship weren’t ordered”. Do you mean NSOrderedSet? Second, I don’t get it how setting one side of relationship would automatically set the other. i.e.

// setting one side of relationship
human.brain = Brain(context: managedContext)

// would is automatically set the other side?
print(brain.human ?? "Human is nil")

Please elaborate. Thanks.

@mhassan Thanks very much for posting your question!

The first statement is giving a hypothetical scenario. In the code example in the book given right above the paragraph you posted, it shows:

if let dog = currentDog,
let walks = dog.walks?.mutableCopy()
as? NSMutableOrderedSet {
walks.add(walk)
dog.walks = walks
}

As you can see, the variable walks in the code is an NSMutableOrderedSet. What the paragraph is saying is, if this were NOT the case, THEN all you need to do would be to set the one side of the relationship. In other words, the reason why the code listed above is the way it is, is because the relationship between the two entities (i.e. Dog & Walks) is ordered.

In your example above, you have a relationship between human, and brain. Core Data allows inverse relationships, which means that setting the relationship on one side will automatically create the opposite link to the other.

e.g. In the case of NO inverse relationship:

A is connected to B, but B has NO connection to A.

e.g. in the case of an inverse relationship:

A is connected to B, and B HAS a connection to A.

In the first scenario, entity B is completely independent of A. B has no relationships of its own. However, in the second scenario, A has a relationship with B, and consequently, B has a relationship with A. Thus, by setting this rule, setting A’s relationship with B, will forge a relationship from B to A.

For your example of Human to Brain & Brain to Human relationship to work, you must make sure that an inverse relationship is set, so that Brain has a relationship to Human (one would hope :wink: )

I hope this answers your question!

All the best.

1 Like

Thank you @syedfa for such a thorough explanation. I did try my example and it’s working. I hope it should work too where relationship is to-many but is unordered.

@mhassan Good to hear! I hope you continue to improve your knowledge in Core Data, and feel free to post any questions you may have!

Take care :slight_smile:

This topic was automatically closed after 166 days. New replies are no longer allowed.