views:

368

answers:

1

I have a Core Data entity, which contains a relationship to another entity. Under certain circumstances, I need to delete the managed objects in the relationship, and at other times no action needs to be taken.

I have the Delete Rule on the entity is No Action because of this manual management.

The problem I have is, where is the best place to enforce these rules? I cannot see any suitable messages to override on NSManagedObject (something that might notify the object it has been deleted and should clear up its relationships).

I would rather not do it higher up in the application logic, because the entity objects can get deleted from array controllers and at different points in the applications, making it necessary to stuff relationship update code at all those levels.

+1  A: 

In your NSManagedObject subclass, override the -prepareForDeletion method and handle the logic there.

UPDATE

You did not specify that you need a solution for retired versions. In that case you can handle it in the -save: call. Just before the save, grab the array of objects to be deleted, iterate over them and then call -prepareForDeletionon each object if it responds to it (using-respondsToSelector:`) and that gives you a future proof way to handle the deletions. You will of course need to check to see if you are running 10.6 or an earlier OS before running this code but that is fairly trivial to write up.

Marcus S. Zarra
-prepareForDeletion is 10.6 only
Simon