From what I have been reading, for a relationship like department <->> employee, I can’t set a simple deletion rule that will cause department to be deleted if the last employee in a department is deleted. Instead, I have to code this rule.
I thought I might use key-value observing, with the didChangeValueForKey: method of the department entity. I want to centralize this delete action into one place, in a DRY way.
I wouldn’t expect that the department entity could delete itself, like this:
- (void) didChangeValueForKey:key {
if (![key isEqualToString @"employee") return;
if (self.employee == NULL)
[self deleteAndSave]; // a category method
}
So I might post a notification, instead
- (void) didChangeValueForKey:key {
if (![key isEqualToString @"employee") return;
if (self.employee == NULL)
[[NSNotificationCenter defaultCenter] postNotificationName:@"empDelete" object:self];
}
and then have the deletion take place in an object where I handle things like my managed object context.
Am I missing something that would make this easier?
A good place for deletion rules is
-(void)prepareForDeletion. You can implement any behavior you need, from the most simplistic to the most sophisticated.When deleting a department, you could per example move all the department’s employees to the parent department, if any. And when you delete an employee, you can check if the parent department still have employees and delete it if left empty. Your call.