views:

835

answers:

3

i wonder if its a wise choice to store images with core data into binary property

say i have a collection of movies and i want to save the image dvd cover into a property the avg size of a cover is 20/30kb (320x480px)

the reason i want to do this is for storage management, once i delete the movie i know the image is also deleted

i'm just not quite sure if it's a good idea, data load, speed?

anyone has experience with this ?

+4  A: 

It seems to me that storing images in a core data isn't a good idea, and I'm pretty sure I've also read it on one of Apple's programming guides. Just consider this, when you fetch your collection, all the images will also be loaded into memory, even if you're only displaying 8 images, your entire image collection will be loaded by core data.

If you want to make sure you delete the image files when a move record was deleted I suggest you listen to notifications by the managedObjectContext and delete files when a movie was deleted:

You can either register for the willSave or didSave notification, each with it's own advantages/disadvantages.

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(contextDidSave:) name:NSManagedObjectContextDidSaveNotification object:managedObjectContext];

Getting the deleted objects:

- (void) contextDidSave:(NSNotification *)notification
{
    NSDictionary *userInfo = [notification userInfo];
    for (NSManagedObject *currObject in [userInfo objectForKey:NSDeletedObjectsKey])
    {
         // Code for deleting file associated with the NSManagedObject, you can still
         // access the managed object's properties.
    }
}
Ron Srebro
There is nothing wrong with storing binary data in Core Data, especially of the image sizes that the OP is working with. Review the two links posted as a note to the question. Anything under 100KB can easily be stored directly in Core Data.
Marcus S. Zarra
Of course it can be done, but in my opinion is just not the best way to do it, unless you can control if the binary data is actually fetched and loaded to memory. Otherwise fetching a 100 records will load 2/3mb into memory for no reason at all.
Ron Srebro
A: 

It occurred to me that you can use another approach which might be better if you're already subclassing NSManagedObject for your movie entity.

You can implement the didSave or willSave method on the NSManagedObject and check isDeleted property. If it is deleted, delete the image from disk.

Ron Srebro
+2  A: 

The best method is to store the path to the image in the managed object and then delete the file in the object's prepareForDeletion method.

TechZen