My CoreData model has an entity that has an Image attribute. I have always managed the images for these entities by storing them on the file system and just maintaining a reference to file in the CoreData attribute, i.e. path.
However I have recently shifted to using child managed contexts for handling editing (so that I can easily discard changes if the user should choose to cancel editing). This is all well and good however I now have an issue of tracking any images changes, specifically if the user changes the image I can no longer just delete the old file (don't want orphaned files building up on the file system) and replace it with the new one, because if the user cancels the changes the old file is now lost.
As I see it I have two options:
Looking for any guidance as to which is the better, and importantly - more performant, approach? Or any other alternate solutions/options...
Thanks!
The first approach would be better. If the save is discardable, it makes sense to do it that way. And unless the images are generally small it's usually better to keep them external.
A good place to delete old images is probably in the managed object's willSave()
method. Look at changedValues
to find the old image name. If it's different from the current value, delete the old one.
To handle rolling back changes, a couple of possibilities come to mind.
NSTemporaryDirectory()
and use willSave()
to move them to a permanent location when saving changes. Then you don't need to do anything on a rollback-- you can let iOS handle clearing the temporary directory for you.