I have a Core Data application with a fairly simple data model. I want to be able to store NSImage instances in persistent storage as PNG Bitmap NSData objects to save space.
To this end, I wrote a simple NSValueTransformer to convert NSImage to NSData in PNG raster format. I register a value transformer with this code in my application file:
+ (void)initialize { [NSValueTransformer setValueTransformer:[[PNGDataValueTransformer alloc] init] forName:@"PNGDataValueTransformer"]; }
In my data model, I set the Transformable image attribute and specified PNGDataValueTransformer as the name of the value converter.
However, my custom value converter is not used. I know this because I posted the log messages in my methods for converting the values -transformedValue: and -reverseTransformedValue , which are not logged, and the data that is stored on disk is simply an archived NSImage, not the PNG NSData object that it should be.
Why is this not working?
Here is the code of my value transformer:
@implementation PNGDataValueTransformer + (Class)transformedValueClass { return [NSImage class]; } + (BOOL)allowsReverseTransformation { return YES; } - (id)transformedValue:(id)value { if (value == nil) return nil; if(NSIsControllerMarker(value)) return value; //check if the value is NSData if(![value isKindOfClass:[NSData class]]) { [NSException raise:NSInternalInconsistencyException format:@"Value (%@) is not an NSData instance", [value class]]; } return [[[NSImage alloc] initWithData:value] autorelease]; } - (id)reverseTransformedValue:(id)value; { if (value == nil) return nil; if(NSIsControllerMarker(value)) return value; //check if the value is an NSImage if(![value isKindOfClass:[NSImage class]]) { [NSException raise:NSInternalInconsistencyException format:@"Value (%@) is not an NSImage instance", [value class]]; } // convert the NSImage into a raster representation. NSBitmapImageRep* bitmap = [NSBitmapImageRep imageRepWithData: [(NSImage*) value TIFFRepresentation]]; // convert the bitmap raster representation into a PNG data stream NSDictionary* pngProperties = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:NO] forKey:NSImageInterlaced]; // return the png encoded data NSData* pngData = [bitmap representationUsingType:NSPNGFileType properties:pngProperties]; return pngData; } @end
objective-c image cocoa core-data
Rob Keniger Oct 21 '09 at 3:34 2009-10-21 03:34
source share