【发布时间】:2010-12-08 14:07:48
【问题描述】:
我有一个具有相当简单数据模型的 Core Data 应用程序。我希望能够将 NSImage 的实例作为 PNG Bitmap NSData 对象存储在持久存储中,以节省空间。
为此,我编写了一个简单的 NSValueTransformer 来将 NSImage 转换为 PNG 位图格式的 NSData。我在我的 App 委托中使用此代码注册值转换器:
+ (void)initialize
{
[NSValueTransformer setValueTransformer:[[PNGDataValueTransformer alloc] init] forName:@"PNGDataValueTransformer"];
}
在我的数据模型中,我将图像属性设置为可转换,并将PNGDataValueTransformer 指定为值转换器名称。
但是,我的自定义值转换器没有被使用。我知道这一点,因为我已将日志消息放在我的值转换器的 -transformedValue: 和 -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
【问题讨论】:
标签: objective-c cocoa image core-data