Jonathan.
Jonathan.

Reputation: 55604

Relationships and entities in CoreData

I have three entities, A, B and C.

Where A has a to-many relationship with B
and B has a to-many relationship with A

Then C has a to-one (correct terminology?) relationship to A, and a to-one relationship to B.

However I want it so C's relationship with A must be an instance of A that is in a relationship with the B related to C.

Normally in code I'd use NSArrays in place of relationships and then in C have store the index of the needed instance. This is my first time using CoreData, so I'm unsure about most of it.

EDIT: To clarify:

enter image description here

Upvotes: 3

Views: 178

Answers (1)

Caleb
Caleb

Reputation: 125037

First, it'd be easier to discuss your situation if you'd avoid using b to mean several different things. There are four relationships in your diagram; for the sake of the discussion, you could name them d, e, f, and g.

To answer your question, you can't and don't need to include the kind of restriction that you're talking about in the model. The model defines relationships between kinds of managed objects, but it doesn't say anything about individual objects. It's usually better to try to think in terms of objects when you're learning Core Data, but you should know that the entities you define in the model are analogous to tables in a relational database: they define can be stored, not what the code should or must (or must not) store.

To restrict C.a to one of the A's in C.b.bs, you'll need to write some code. If C.a is only set in one place, you might choose to implement the restriction in that code. If the restriction is essential to the proper operation of C, you might instead (or in addition) choose to add a check to the setter for C.a that verifies that the A is one of the allowed ones. You may also need to fix up the setter for C.b so that if C.b changes, it verifies that C.a is still valid and does something appropriate if it's not (clear C.a, pick a new C.a, refuse to accept the new C.b, post a notification, throw an exception, whatever).

Upvotes: 1

Related Questions