6
votes

I have a album photo core data model. The photo entity has a column for the path of the actual photo files saved on disk. What is the the best practice for delete a photo and a album? Do I have to manually delete the file on disk before delete the item in core date? It's easy for a photo object. But for a album, the photos could have been deleted by the cascade deletion rule, now need to be looped one by one to handle the files.

What's the best practice for my case?

(I decided no to use "allow external storage" for other concerns)

1

1 Answers

7
votes

You could override prepareForDeletion in the Photo managed object subclass and delete the photo file there:

- (void)prepareForDeletion
{
    [super prepareForDeletion];
    [[NSFileManager defaultManager] removeItemAtPath:self.path error:nil];
}

Then deleting the Photo object automatically removes the corresponding file, and it works also if the object is deleted due to some cascading delete rule.

UPDATE: As Xiaochao Yang noticed, overriding didSave might be the better solution, in particular if you use the undo capability of a managed object context. Compare the various answers to "How to handle cleanup of external data when deleting Core Data objects".