Question

I'm looking for the best way to store multiple images in one core data object. I tried to store a UIImage object in Core Data directly. Works fine!

Nevertheless, I read in some forums to transform the UIImage data to PNG and store it as binary data. On my iPhone 5s this was very slow.

What are the pros and cons? Are there any other solutions?

Thanks!

Was it helpful?

Solution

If you are targeting iOS 6.0 or greater or OSX 10.8 or greater you can turn on Allows external storage (select your attribute and look at the Data Model Inspector in the Core Data Model Editor) and let Core Data decide if it wants to store your image data in the database or in an external file (if it is above a certain size).

OTHER TIPS

There is one and only one good way to save images to database - don't do it.

Just write it to a file in some folder and store only the file name (or relative path). Don't store absolute file paths, that would cause problems when updating the app from app store.

Reasoning:

  1. Compared to other types of data, image data are big. It makes the saving (and loading) of managed objects significantly slower. It is very helpful to have image loading/saving independent on the DB code. You can load object metadata or search by metadata and load the actual image (the slowest operation) only when needed.

  2. There is no need to have images in the database, you never search images by data.

Don't store an image in Core Data. Store the path to the image in Core Data.

You can save any image to the Library or Documents directory of your application sandbox.

Simple example:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
NSString *libraryDirectory = [paths objectAtIndex:0];
NSString *path = [libraryDirectory stringByAppendingPathComponent:fileName];
NSData *imageData = UIImagePNGRepresentation(image);
[imageData writeToFile:path atomically:YES];

// Save file name to Core Data. Don't store absolute paths.

Some tips to manage images with Core Data without loosing too much performances:

If your image is really small (~100 ko) store it in the same entity with the others informations relative to the image.

Else I advice you to store only the path of the picture in CoreData and save it in the device.

Otherwise, if you really want to keep your images in CoreData regardless of its size, can you show us the code that is very slow ?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top