views:

55

answers:

1

I have two objects, a Trip and a Place. A Trip represents a journey from one Place to another Place, ie. a Trip needs a fromPlace and a toPlace. So, this is a 1-to-2 relationship, but I need to know which is the "from" and which is the "to". I am not sure how to model this in Core Data. I have created two entities (Trip, Place), and now I want to setup the relationship(s) so I have a fromPlace and a toPlace. Do I need to add an extra field on the Place entity called isFrom, or similar?

If this was in a database, I would just have a id column on the Place table, and then two columns in the Trip table - fromPlaceId and toPlaceId. How do I achieve something similar in Core Data?

+1  A: 

Do I need to add an extra field on the Place entity called isFrom, or similar?

Yes. It's better for you not to think of Core Data as a wrapper around a database; the database intuition sometimes gets in the way.
Don't first think in terms of database and then try to translate it into Core Data. While you're learning how to use Core Data, just think of it as a system of objects which can be saved into a file and persist between two launches of the app.

Then, from the point of view of object-oriented programming, you have a class Trip which has two instance variables fromPlace and toPlace of class Place.

You want to make it persist on a file. So you create an entity Trip which has two relations fromPlace and toPlace, both of which is of entity Place. That's it!

In more detail, fromPlace and toPlace in Trip are both to-one relationships. In Place, you make two to-many relationships, say tripsStartingHere and tripsEndingHere. Then you set tripsStartingHere as the inverse of fromPlace, and tripsEndingHere as the inverse of toPlace.

Yuji
Thanks for the answer, but you've confused me a little with that last part :) Should I have one relationship between Trip and Place which is a 1-to-2 relationship, and an isFrom field on the Place entity? From your last sentence it sounds like I should have two relationships going to Place, but then I can't set the inverse?
alku83
I ended up putting an isFrom field on the Place entity.
alku83