8

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.

Brent
  • 103
  • 1
  • 5
  • do you mean you have a separate entity for Image (where the image data is stored) with a relationship to your "main" entity, or that you actually store the filepath to the image in your "main" entity (i.e. a property) and save the images in the documents folder? – Rog Feb 22 '11 at 01:25
  • Yes, I have a main entity that has a relationship to the image entity. Inside the image entity there is a path to the image stored in the documents folder. I set things up this way because everything I have read advises against storing large images in Core Data. Obviously, I want the image files to be deleted when the image entity goes away and was wondering if there is an elegant way to handle this in Core Data. – Brent Feb 22 '11 at 01:44

4 Answers4

13

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 - didSave is 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:, plus awakeFromSnapshotEvents: 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.]

rgeorge
  • 7,385
  • 2
  • 31
  • 41
  • 3
    Deleting images in `willSave` can cause you to delete images that are still referenced in the persistent store. You probably want to avoid this. See my answer for details. – Phil Calvin Jan 10 '12 at 18:39
  • 1
    Turns out this works only, if the context was saved between adding and deleting the „image“. If it was not, neither -willSave nor -didSave will be called. See my question: [How to handle cleanup of external data when deleting *unsaved* Core Data objects?](http://stackoverflow.com/questions/25603227/how-to-handle-cleanup-of-external-data-when-deleting-unsaved-core-data-objects) – MartinW Sep 01 '14 at 10:00
  • `willSave` & `didSave` are called right before & after `prepareForDeletion:`, and won't be called after undo/redo. The best solution for supporting undo/redo with handling external files, should be using `awakeFromSnapshotEvents`. check it out here: http://stackoverflow.com/a/25614035/886215 – CocoaBob Dec 11 '15 at 17:41
4

In your Image class, implement -didSave. In this method, check whether [self isDeleted] and if it's YES, delete the image files from disk.

It's important to do this in -didSave rather than -willSave particularly if you have multiple managed object contexts associated with your persistent store. willSave is sent before Core Data discovers and reports (as a save error) any merge conflicts. This means you could potentially receive willSave either:

  1. Multiple times if you implement a merge strategy that merges objects and re-tries the save
  2. Before a save that never commits to the persistent store due to a merge conflict

Deleting the image files prematurely could cause a crash later when those images are accessed from another managed object context.

Phil Calvin
  • 5,077
  • 2
  • 41
  • 35
  • Turns out this works only, if the context was saved between adding and deleting the „image“. If it was not, neither -willSave nor -didSave will be called. See my question: [How to handle cleanup of external data when deleting unsaved Core Data objects?](http://stackoverflow.com/questions/25603227/how-to-handle-cleanup-of-external-data-when-deleting-unsaved-core-data-objects) – MartinW Sep 01 '14 at 10:01
  • @MartinW: Correct, this will not save the image data unless the database is also saved. I'm of the opinion that's correct, but like many things it depends on the application's needs. – Phil Calvin Sep 12 '14 at 14:45
2

I would suggest overriding the image entities prepareForDeletion method to delete the image file on disk. The method will only be called with the image entity object is actually deleted.

TechZen
  • 64,370
  • 15
  • 118
  • 145
  • Hmmm. Given the sparse documentation on NSManagedObject methods I will just need to try some scenarios involving willSave vs. prepareForDeletion to figure out exactly when they get called. I do not want to get into a situation where I delete the image file but the deletion never happens. (say because the app crashed or was terminated before it could execute the save) Thanks. – Brent Feb 22 '11 at 21:37
  • prepareForDeletion on a child object involved in a cascade delete happens after the parent relationship has already been nullified. So it is somewhat limited. I had a case where part of the path to the filename was derived from a parent property. Poof went that logic. – Καrτhικ Aug 24 '12 at 17:17
0

The best practice would be (which I think would be the same to what @Rog implied) to have an entity for stored images, and make your objects have a relationship to that entity, rather than storing paths in each object. In that case, you can just find one object which represents the picture to be deleted and delete it, than the reverse relationship can be automatically nullified.

MHC
  • 6,405
  • 2
  • 25
  • 26