4

My object graph contains two entities: Author and Book with one to many relationship (one author may write many books)

I wish that when a book is deleted, the author will be deleted as well but only if there are no other books in the database connected to that author. (that means that author should be deleted only when the last author's book is deleted)

What is the best way to do this?

Joshua
  • 1,974
  • 2
  • 23
  • 39

2 Answers2

3

You can put your deletion logic in your -prepareForDeletion method on your NSManagedObject. You should be able to assert any policy you want then.

Taryn
  • 242,637
  • 56
  • 362
  • 405
adonoho
  • 4,339
  • 1
  • 18
  • 22
  • Joshua, ignore my answer. Adonoho's suggestion will make for much cleaner, more easily maintained code. I'll adopt it myself. (Thanks again, Adonoho.) – Wienke Feb 14 '12 at 04:47
  • Thank you both for your help! If I am going with Adonoho's suggestion, what delete rule should I set in each entity? – Joshua Feb 14 '12 at 15:14
  • Joshua, if you are going to build custom rules, then you should go with the nullify setting. Basically, you don't want CD doing anything. Andrew – adonoho Feb 15 '12 at 13:26
1

I wish there were such a thing as a conditional cascade delete rule, but on the assumption that there isn't, I have used a regular nullify rule, and then implemented some special handling for the deletion, like this:

- (IBAction) deleteBook:(id)sender { // or whatever method handles the deletion
    NSManagedObjectContext *context = // get a ref to the context
    Book *bookToDelete = // get the selected book
    if (bookToDelete.authorMember && [bookToDelete.authorMember.bookMembers count] == 1)
        [context deleteObject:bookToDelete.authorMember]; 
   [context deleteObject:bookToDelete];
}
Wienke
  • 3,723
  • 27
  • 40