Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The best practice for deleting core data items where path is stored as text and actual file is saved on disk?

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)

like image 348
X.Y. Avatar asked Jul 21 '13 06:07

X.Y.


1 Answers

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

like image 84
Martin R Avatar answered Oct 13 '22 12:10

Martin R