简体   繁体   中英

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.

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];
}

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/ .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM