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

后端 未结 6 614
故里飘歌
故里飘歌 2020-11-27 17:08

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

6条回答
  •  心在旅途
    2020-11-27 17:51

    If I'm not mistaken, your value transformer has a reversed direction. I do the same thing in my application, using 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];
    }
    

    While this is for the iPhone, you should be able to swap in your NSImage code at the appropriate locations. I simply haven't tested my Mac implementation yet.

    All I did to enable this was to set my image property to be transformable within the data model, and specify the name of the transformer. I didn't need to manually register the value transformer, as you do in your +initialize method.

提交回复
热议问题