开发者

Core Data and Relationships

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 relationsh开发者_StackOverflowip, 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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜