How should I store UIImages within my Core Data database?

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.

Leave a Comment