How to define a conditional cascading delete rule in Core Data?

There are two objects in my graph of objects: the author and the book with a one-to-one relationship (one author can write many books)

I want the author to also be deleted when deleting a book, but only if there are no other books in the database associated with this author. (this means that the author should be deleted only when deleting the last book of the author)

What is the best way to do this?

+4
source share
2 answers

You can put your delete logic in your -prepareForDeletion method on NSManagedObject . You should be able to approve any policy you want next.

+3
source

I would like for such a conditional cascading delete rule to exist, but on the assumption that it is not there, I used the correct nullify rule and then implemented some special handling for the delete, for example:

 - (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]; } 
+1
source

Source: https://habr.com/ru/post/1396298/


All Articles