Search code examples
ioscore-datansundomanager

NSUndoManager detect actual deletion of Core Data entities


I am looking for a way to know when a Core Data entity is really deleted from the data store.

I hooked up an NSUndoManager to my NSManagedObjectContext and so far everything is working fine.

Current situation

I'm building an app that allows users to create Rooms and add some pictures in each room. When the user wants to create a new room, I create an action in the NSUndoManager with the following code:

[[[NSManagedObjectContext MR_defaultContext] undoManager] beginUndoGrouping];
[[[NSManagedObjectContext MR_defaultContext] undoManager] setActionName:@"Create Room"];

and then undo when the user presses cancel. This causes all changes to be undone and the freshly created temporary Room object to be deleted.

A user then takes Pictures for this temporary Room object. I store the actual image on disk and the filePath as an NSString attribute in the Picture entity. When the user manually deletes a picture in a room, I delete the image from disk in the prepareForDeletion: method on Picture.

Problem

Now imagine the situation where the user later opens the Room entity, deletes a Picture and then presses cancel. The NSUndoManager now undoes all the actions. When the user deleted the Picture, the actual image was deleted from disk. However, the Picture object is restored by the NSUndoManager and filePath is now set to an image that's physically deleted.

Is there a way to know when a Picture is really deleted (i.e. in prepareForDeletion:)? I mean, it was deleted by the user AND not brought back by an undo operation?

Should I really not delete anything and clean up the unlinked photo's from my app documents every x days? Or should I keep track of which Pictures the user deleted and queue them up for deletion when the user presses save instead of cancel?


Solution

  • "Solved" this issue by just never deleting from disk by any user action, and to run a cleanup method every time the app starts.