Deleting a core data object on iOS is a really common task, I'd say. But it has a common problem that I just can't figure out myself: if the instance has relations set, the deletion fails with NSValidationRelationshipDeniedDeleteError
(1600). This is the case even if all relations, including inverse, are set to "optional". Apple's documentation says this error code denotes that "some relationship with delete rule NSDeleteRuleDeny is non-empty". This is not the case here; all relationships have a delete rule of "nullify".
I even tried with the simplest relation I could think of, using the employee and department example of Apple's documentation. I can delete an employee as long as it has no department set.
I found this thread about this problem; the solution there is to set all relations to nil before saving the MOC. This indeed works, but it does not make the faintest sense to me.
My question: is this really common practice? How does this make sense? What does everybody else do to delete Core Data objects with relations?
PS: In case anybody is interested, this is my code to clear the relations; entityInstance
is the instance to be deleted. The code is generic for my app, meaning it clears all relations of the entity to be deleted:
NSEntityDescription *ed = entityInstance.entity;
NSDictionary *relations = [ed relationshipsByName];
NSArray *keys = [relations allKeys];
[keys enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
[entityInstance setValue:nil forKey:(NSString*) obj];
}];