Ios – Core Data multiple relationships to same entity

core-dataentityiosrelationship

I've been studying Core Data quite a bit now, and I've now decided it's time to use it in a new project I'm doing.

Having never use it in a working project I've just come across a few issues I would like to get the communities feedback on.

I'm doing a location based application and I would like to store "outings" in my Core Data model, so for each trip I have some traditional information such as date, distance, description etc… But I also need to save location information which I'll need to plot some points on a map.

So I have a "to" and "from" object per trip, I've created a MapPoint entity with latitude, longitude and location name attributes. On my Trip entity, I've added a "to" and a "from" relationship who's destination is MapPoint.

But what do I do with the inverse property?

Because Xcode seems to give a warning it I leave it as "No inverse".

I needed to create 2 relationships on MapPoint to reference back to the Trip to the "to" and another relationship referencing the "from" relationship of Trip.

Is this correct ? I can't quite understand.

I have a similar issue with a User Entity where this is being used in several other Entities, should I be implementing an inverse relationship back to each Entity which uses User?

To keep Xcode happy it seems I need to create a relationship on User back to Trip, and back to other Entities I'm using such as an Upload, Picture entities etc… it seems to me disturbing to think a Trip has a User object, which would then have prepared to link back to an Upload/Photo… which has nothing to do with that Trip.

Best Answer

If you want to support inverse relationships for your to and from relationships, you can just add appropriate relationships to your MapPoint entity. Call them tripTo and tripFrom, or whatever seems appropriate to you, and set those as the inverse relationships for your to and from relationships, respectively.

As the docs explain, you're not required to model a relationship in both directions, but doing so makes life easier. What happens, for example, when a user is deleted? If you have a number of other entities related to User, then you need some way to figure out which objects were related to that user so that you can update them. If you have inverse relationships, Core Data can automatically update any related objects using the deletion rule (like nullify) that you choose. Without inverse relationships, it's up to you to fix up any related objects.

Related Topic