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?
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
Tripwhich has two instance variablesfromPlaceandtoPlaceof classPlace.You want to make it persist on a file. So you create an entity
Tripwhich has two relationsfromPlaceandtoPlace, both of which is of entityPlace. That’s it!In more detail,
fromPlaceandtoPlaceinTripare both to-one relationships. InPlace, you make two to-many relationships, saytripsStartingHereandtripsEndingHere. Then you settripsStartingHereas the inverse offromPlace, andtripsEndingHereas the inverse oftoPlace.