iosswiftcore-datamagicalrecord

CoreData - Managing file references in child context


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:

  1. I track the image changes in my business layer and only remove any old images once the context is saved, or conversely delete any new images if the context is discarded/cancelled.
  2. I change my image attribute to a Binary Data type (checking 'allows external storage') and let CoreData manage the data... in which case everything should just work.

Looking for any guidance as to which is the better, and importantly - more performant, approach? Or any other alternate solutions/options...

Thanks!


Solution

  • 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.