I have two classes A and B with a many-to-one relationship from A to B (multiple A objects may reference the same B). The question is, if the delete rule on the A side is C
I had the same goal as you apparently had (delete B as soon as the last referenced A is deleted). It took me longer than expected to get this right. Particularly because
-prepareForDeletion
Here's what worked for me if anybody's interested (I'll use Department <-->> Employee because it's easier to read):
In Employee:
- (void)prepareForDeletion {
// Delete our department if we we're the last employee associated with it.
Department *department = self.department;
if (department && (department.isDeleted == NO)) {
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"isDeleted == NO"];
NSSet *employees = [department.employees filteredSetUsingPredicate:predicate];
if ([employees count] == 0) {
[self.managedObjectContext deleteObject:department];
}
}
}
Other people have suggested putting this logic into -willSave
in Department. I prefer the solution above since I might actually want to save an empty department in some cases (e.g. during manual store migration or data import).