I am developing an application which demands around 100 images or maybe more to be pre-inserted into the Core Data database along with other related information.
Now I can easily add other data by just writing a few lines of code but for UIImages I am unsure how to do it without writing a lot of code. I was wondering: is there anyway to do this easily, or if there isn't what's the best way to achieve this with the least amount of effort.
Also, is it okay to store images in a Core Data database or should we only only save the addresses of images on the local file system?
The persistent store should be located in the AppData > Library > Application Support directory.
When you declare a property as Transformable Core Data converts your custom data type into binary Data when it is saved to the persistent store and converts it back to your custom data type when fetched from the store. It does this through a value transformer.
Storing images within a Core Data database is pretty easy to do. You just need to mark your image attribute as a transformable one and create a subclass of NSValueTransformer. Within that subclass, add code like the following:
+ (Class)transformedValueClass { return [NSData class]; } + (BOOL)allowsReverseTransformation { return YES; } - (id)transformedValue:(id)value { if (value == nil) return nil; // I pass in raw data when generating the image, save that directly to the database if ([value isKindOfClass:[NSData class]]) return value; return UIImagePNGRepresentation((UIImage *)value); } - (id)reverseTransformedValue:(id)value { return [UIImage imageWithData:(NSData *)value]; }
For your transformable attribute, specify this subclass's name as the Value Transformer Name.
You can then create an NSManagedObject subclass for the entity hosting this image attribute and declare a property for this image attribute:
@property(nonatomic, retain) UIImage *thumbnailImage;
You can read UIImages from and write UIImages to this property and they will be transparently changed to and from NSData to be stored in the database.
Whether or not to do this depends on your particular case. Larger images probably should not be stored in this manner, or at the least should be in their own entity so that they are not fetched into memory until a relationship to them is followed. Small thumbnail images are probably fine to put in your database this way.
A good example of the image transformer as described above is in the iPhoneCoreDataRecipes demo application.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With