In your "image" object class, execute willSave . Check [self isDeleted] and delete the file, if so. This delays the actual deletion of the file until the storage is saved, giving you some cancellation. Set up appropriate cascading rules to remove image objects when their owner leaves and there you go.
[eta: Phil Calvin's comment below on the right - didSave is probably the best place if you use multiple contexts.]
[ETA. much later:] MartinW raises an excellent point - if the object has never been saved, it will / will not be saved. Deleting an unsaved object simply does not insert it from the context and throws it out without special life cycle events. And just to complicate matters more, you can “cancel” and “redo” the deletion, including (I think) of this kind.
A few considerations that come to mind:
This might be the case of an override of prepareForDeletion: plus awakeFromSnapshotEvents: to catch the deletion and re-deletion. To support undo / redo, you don’t just need to delete the file in place, but use some kind of registry “for deletion” (for example, a common changed set of file names to clean when a save notification is sent). Then / didSave will be taken out of the image.
Or, if you can live with BLOB fields instead of files, you can check the "allows external storage" field on a binary property, put jpeg data there and get some (not all) advantages of storing files without (most of) headaches. A small binary will be stored in db; something more than a private threshold will be disconnected into a separate hidden data-driven file. However, the main data still needs to load all of this into NSData if the object crashes. I use this approach for small user avatar images.
Finally, if nothing else is stored in the images directory, you can register for didSave notifications and manually clear it after saving. Run a selection request for all Image.filename properties, compare it with the list of directories with the dir image in the question, delete it if necessary. I use this approach as my “big stick” during development to make sure that everything else does what it needs.
[Let me know of successes or difficulties with these approaches, and I will keep this in the know.]
rgeorge
source share