I am fairly new to Core Data and have run into an issue which others must have encountered.
My data model includes images and I am keeping those external to the database and simply storing a path/URL to the image. (as recommended in one of Apple’s Core Data presentations)
When deleting my image object I can manually traverse relationships and remove the image files but I am wondering if there is a more elegant way to do this.
The ideal solution would be tied to the image object somehow and would work with Core Data undo/redo.
In your “image” entity class, implement
willSave. Check[self isDeleted]and delete the file if so. This postpones actual deletion of the file until the store is saved, which gives you some undo-ability. Set up appropriate cascade rules to delete the image entities when their owner goes away, and there you go.[eta.: Phil Calvin’s comment below is right –
didSaveis probably a better place, if you’re using multiple contexts.][eta. much later:] MartinW raises an excellent point – if the object has never been saved, will/did save won’t get called. Deleting an un-saved object just un-inserts it from the context and throws it away, with no special lifecycle events. And just to complicate matters more, you can “undo” and “redo” a deletion, including (I think) this kind.
A few approaches that come to mind:
This might be a case for overriding
prepareForDeletion:, plusawakeFromSnapshotEvents:to catch un-deletion and re-deletion. To support undo/redo, you’ll need to not simply delete the file on the spot, but use some kind of “to be removed” registry (e.g. a shared mutable set of filenames to clean up when a save notification is posted). Then will/didSave are out of the picture.Or, if you can live with BLOB fields instead of files, you could check the “allows external storage” box on a binary property, put the jpeg data there, and get some (not all) of the advantages of file storage without (most of) the headaches. Little binary will be kept in the db; anything bigger than a private threshold will be shunted out into a separate hidden core-data-managed file. Core data still has to load the whole thing into an NSData when faulting in the object, though. I use this approach for “user avatar”-type small images.
Finally, if nothing else is kept in the images directory, you could register for didSave notifications and manually clean up after any save. Run a fetch request for all the Image.filename properties, compare it to a directory listing of the images dir in question, delete as appropriate. I use this approach as my “big stick” during development to make sure everything else is doing what it should.
[Let me know of successes or hardships with these approaches and I’ll keep this up to date.]