Alex Rivera | Logout

Why is my transformable Core Data attribute not using my custom NSValueTransformer?

Asked 2009-10-21T03:34:12.263
11

I have a Core Data app with a fairly simple data model. I want to be able to store instances of NSImage in the persistent store as PNG Bitmap NSData objects, to save space.

To this end, I wrote a simple NSValueTransformer to convert an NSImage to NSData in PNG bitmap format. I am registering the value transformer with this code in my App delegate:

+ (void)initialize
{
    [NSValueTransformer setValueTransformer:[[PNGDataValueTransformer alloc] init] forName:@"PNGDataValueTransformer"];
}

In my data model, I have set the image attribute to be Transformable, and specified PNGDataValueTransformer as the value transformer name.

However, my custom value transformer is not being used. I know this as I have placed log messages in my value transformer's -transformedValue: and -reverseTransformedValue methods which are not being logged, and the data that is being saved to disk is just 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:NSInternalInconsistencyExcep
Edit
Report

1 Answer

0

Check out the example code here.

Does this do what you want?

@implementation UIImageToDataTransformer


+ (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];
}
answered 2009-11-24T21:28:51.430

Your Answer