max_
max_

Reputation: 24481

How to store UIImages and NSArrays in a CoreData file? What attribute type to use?

I am just beginning core data, and I wanted to know which attribute type I need to use so that I could store a UIImage and NSData in a CoreData 'file'. By this I mean what do I need to set the Attribute Type to.

Upvotes: 0

Views: 1229

Answers (3)

Yonat
Yonat

Reputation: 4608

UIImage can be stored as Transformable without writing any additional code, by setting the transformer to NSUnarchiveFromDataTransformerName.

See explanation at http://ootips.org/yonat/uiimage-in-coredata/ .

Upvotes: 3

mackworth
mackworth

Reputation: 5953

For the image, create a type Transformable, and then add the following to your .m file:

@implementation ImageToDataTransformer

+ (BOOL)allowsReverseTransformation {
    return YES;
}

+ (Class)transformedValueClass {
    return [NSData class];
}

- (id)transformedValue:(id)value {
    NSData *data = UIImagePNGRepresentation(value);
    return data;
}

- (id)reverseTransformedValue:(id)value {
    UIImage *uiImage = [[UIImage alloc] initWithData:value];
    return [uiImage autorelease];
}

Upvotes: 3

The type is "Binary Data", which I believe ends up as an NSData type in the property on the entity.

However for a UIImage, you cannot just store that in a database as-is - you'll have to convert it to an NSData object first (convert to a JPG or PNG file) or store the UIImage to disk (as a PNG or JPG) and then store the file path in the database.

Unless it's a really small image you are better off not holding it in the database.

Upvotes: 2

Related Questions