我有一个核心数据应用程序,具有相当简单的数据模型。我希望能够将 NSImage 实例作为 PNG Bitmap NSData 对象存储在持久存储中,以节省空间。
为此,我编写了一个简单的 NSValueTransformer 将 NSImage 转换为 PNG 位图格式的 NSData。我正在我的应用程序委托中使用以下代码注册值转换器:
+ (void)initialize
{
[NSValueTransformer setValueTransformer:[[PNGDataValueTransformer alloc] init] forName:@"PNGDataValueTransformer"];
}
在我的数据模型中,我已将图像属性设置为 Transformable,并指定PNGDataValueTransformer
作为值转换器名称。
但是,我的自定义值转换器没有被使用。我知道这一点,因为我已将日志消息放入我的值转换器中-transformedValue:
and -reverseTransformedValue
没有被记录的方法,并且保存到磁盘的数据只是一个存档的 NSImage,而不是它应该是的 PNG NSData 对象。
为什么这不起作用?
这是我的值转换器的代码:
@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
如果我没记错的话,你的价值转换器的方向是相反的。我在我的应用程序中做了同样的事情,使用如下代码:
+ (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];
}
虽然这是针对 iPhone 的,但您应该能够在适当的位置交换 NSImage 代码。我只是还没有测试我的 Mac 实现。
为了实现这一点,我所做的就是将图像属性设置为可在数据模型中转换,并指定转换器的名称。我不需要像您在 +initialize 方法中那样手动注册值转换器。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)