views:

15

answers:

1

Core Data is throwing me for a loop. I have two objects:, Card and CardSet, which are in a many-to-many relationship with each other, i.e. you could have cards 1, 2, and 3 in CardSet A and cards 2, 4, and 5 in CardSet B.

I am trying to set up my delete actions so that:

  1. If I delete a Card, it is removed from all CardSets to which it belongs. (i.e., delete Card 2, then CardSet A = {1, 3} and CardSet B = {4, 5})
  2. If I delete a CardSet, then all of the cards in the set are deleted EXCEPT those which belong to another set. I.e. delete CardSet A, then CardSet B remains {2, 4, 5}.

My data structure has two relationships which define this many-to-many relationship: CardSet.cards and Card.cardSets. The delete action for CardSet.cards is cascade (so if I delete a CardSet, all of its cards are deleted) and my delete action for Card.cardSets is null (so if I delete a single card, the cardSets are not nuked as well).

However, with this current setup if I delete CardSet A, then CardSet B remains {2, 4, 5} BUT Card 2 has actually been deleted from the data store which leads to a core data error when trying to access the CardSet. What should I be doing here to make sure that cards are not deleted if they are still being held by another CardSet?

+1  A: 

You want to set Card.cardsets to deny instead of null. That way, the card will not be removed until it is no longer related to any CardSet.

From the Core data Programming Guide

Deny

If there is at least one object at the relationship destination, then the source object cannot be deleted.

For example, if you want to remove a department, you must ensure that all the employees in that department are first transferred elsewhere (or fired!) otherwise the department cannot be deleted.

TechZen
Unfortunately this doesn't do the trick, it simply makes it impossible to delete items.
Jason