Add to cart functionality - Core data
I am trying to create the best possible design for the following scenario.
Category -> The list of products
In the tableview where the list of products is shown, the user has the option to add that product to the cart. So, whenever the user opens the cart, he can see all of the products he has added.
My question is how can I best setup this functionality in Core Data? Is the best solution to maintain a separate Cart Entity? Or is a relationship the right way to do it?, If yes can you please tell me what kind a relationship it should be between Cart & Product?
Make a Cart entity as you suggested with a To-Many relationship with a CartProduct entity. Cart entity can contain 'meta' information about the purchase and CartProduct would link to the actual Product entity.
The type of relationship between a CartProduct entity and Product entity would essentially be a 1-1, so in Xcode, in the data model editor, with the CartProduct entity selected, be sure to add the Product entity as a relationship in the Relationships section and leave the To-Many Relationship setting unchecked. The values would be something like this:
- Relationship: Product
- Destination: Product
- Inverse: CartProduct
Then, select the Product entity in the editor and double check that a relationship exists that looks something like this (again, make sure that the To-Many Relationship setting is unchecked):
- Relationship: CartProduct
- Destination: CartProduct
- Inverse: Product
The above should get you started.