0
votes

I have a one-to-many relationship in Core Data. For example, A->B where A is a department, B is employees. A department can have many employees and one employee can only have one department.

I set A->(casacade)->B, so if I delete A, all Bs will be deleted.

On the contrary, I can also delete B. In a situation when I delete the last B, is there any delete rule so that A will get deleted automatically? Or I have to delete A programmatically? Anything I should be careful about?

1
I'm not a Core Data expert, but I believe that you can constrain the relationship to require a minimum number of Bs for each A, but it is up to you to detect through validation that we have entered an invalid state (because the last B was deleted) and take appropriate action. developer.apple.com/library/mac/documentation/Cocoa/Conceptual/…matt

1 Answers

1
votes

In our sample app for our book https://www.objc.io/books/core-data/ we show exactly this use case.

Basically what you want to do is override prepareForDeletion (it gets called when your object is deleted). There you want to check if the array or set of objects that are no deleted is empty or not:

Here a country's prepareForDeletion checks it's (parent) continent has any non-deleted countries left:

public override func prepareForDeletion() {
    guard let c = continent else { return }
    if c.countries.filter({ !$0.deleted }).isEmpty {
        managedObjectContext?.deleteObject(c)
    }
}