naeger
naeger

Reputation: 410

CoreData modelling inverse relationship

Apple's documentation suggests the use of inverse relationships when modelling data models in CoreData.

I have the following example:

A Book (Entity) has several "pages" and one "frontCover" and one "backCover". A Page (Entity) is in one "book" (so "book" is the inverse of "pages").

OK so far, that's the standard case...BUT now, my problem:

I only have one class Cover (Entity). A Cover (Entity) is on one "book". On this "book" the Cover is EITHER the "frontCover" OR the "backCover". So, the inverse of "book" is EITHER "frontCover" OR "backCover".

This cannot be modelled in CoreData. A relationship can only be the inverse of one relationship, but not of EITHER this OR that relationship.

What is the best way to model this? Unidirectional relationships (no invers)?

Thanks for your answers, Chris

Upvotes: 1

Views: 742

Answers (3)

Anonymous White
Anonymous White

Reputation: 2159

I just want to add.

One way is to have 2 subentities. But that's useful only if FrontCover and BackCover differs a lot.

If they are exactly the same object, you should instead use an enum in the entities.

That enum differentiate whether the cover is frontCover or BackCover.

Then you set only 1 "to many" relationship from book to cover.

The purpose of coredata is to save your data. Your logic should be in the code anyway.

Also creating two subEntities is essensially the same with westSider's answer. Sub entities simply add another relationship on the original one.

Upvotes: 0

westsider
westsider

Reputation: 4985

You could do something like the model below (first image). This would leaving of Cover's inverse relationships as nil. This doesn't feel right to me, though.

Another option (second image) would be to give Book a 'covers' relationship which references 2 Cover objects, and give Cover an isFront boolean attribute. This would allow for inverse relationship called 'book'.

enter image description here

enter image description here

Upvotes: 2

Scott Little
Scott Little

Reputation: 1939

One way to do it could be to create Cover as an "abstract" entity with two sub entities - FrontCover & BackCover. Then you could create the relationship & inverse to each of those.

Upvotes: 2

Related Questions