简体   繁体   中英

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, ie 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!

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.

  • Handle this in whatever code rolls back the change by looking at the about-to-be-rolled-back new instance and removing its image file.
  • Always put new images in 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM