CoreData: multiple copies of the same item linked to another?
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 ar开发者_Python百科ound that?
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.
精彩评论