views:

27

answers:

1

In Core Data is there a way to have one instance of an object to have multiple links to another? This is best understood with an example. You have a shopping cart object, ShoppingCart, and you have books, Book. How do you properly put multiple copies of the same book into the cart?

No matter how many times you run [shoppingCart addBooksObject:book]; it will only show up once.

Right now I have a many-to-many connection between the two, but since shoppingCart.books is a set, it removes the duplicates. How do I get around that?

+1  A: 

You get around it by using an appropriate data model. :-)

This is the classic "line item" problem. There's Product, Invoice, and Line Item. In your case, the book is the product and the shopping cart the invoice. You don't put a product in the cart, you put a line item (that is linked to the product) in the cart.

The line item(s) belong to the cart (one per product) and hold the quantity attribute (and maybe a computed subtotal based on some volume discount based on quantity). In other words, you need an intermediary entity (maybe CartItem?) to hold the relationship and the quantity.

Joshua Nozzi
So basically you create the join table yourself. That will work just fine. Thank you.
RyanJM
You'll do yourself a grave injustice by thinking of Core Data in terms of relational databases. The knowledge definitely helps but if you apply it too rigidly you'll miss a lot of the useful simplifications Core Data offers.
Joshua Nozzi