Core Data Image Won't Load Into NSTableView Image Cell

折月煮酒 提交于 2019-12-02 08:22:36

I'm not sure what is happening to cause your problem but there's an easy way to find out. Hook up an NSValueTransformer to the binding. Then in that transformer you can log stuff to find out if you're passing a nil value, or you can transform your data value into an NSImage and pass that back… basically you can do whatever you want in the transformer class. Here's one I use on image data in a core-data model.

@interface DataToImageTransformer : NSValueTransformer {

}

@end


@implementation DataToImageTransformer

+ (Class)transformedValueClass {
    return [NSImage class];
} // the class of the return value from transformedValue:

+ (BOOL)allowsReverseTransformation {
    return YES;
} // if YES then must also have reverseTransformedValue:

- (id)transformedValue:(id)value {
    if (value == nil || [value length] < 1) return nil;
    NSImage* i = nil;
    if ([value isKindOfClass:[NSData class]]) {
        i = [NSKeyedUnarchiver unarchiveObjectWithData:value];
    }
    return i;
}

- (id)reverseTransformedValue:(id)value {
    if (value == nil) return nil;
    NSData* d = nil;
    if ([value isKindOfClass:[NSImage class]]) {
        d = [NSKeyedArchiver archivedDataWithRootObject:value];
    }
    return d;
}

@end

In AppController class you initialize the transformer:

+ (void)initialize {
    DataToImageTransformer *transformer = [[DataToImageTransformer alloc] init];
    [NSValueTransformer setValueTransformer:transformer forName:@"DataToImageTransformer"];
    [transformer release];
}

Then in Interface Builder you put "DataToImageTransformer" in for the binding. Now you have control over the binding and can do as I explained earlier in the transformer class. Note that I'm using NSKeyedArchiver to convert an NSImage to data and back again but you can use tiffRepresentation or any other method you want in its place.

If anyone is having issues with the suggested technique with Xcode 6. I created a Swift project, using the Document based app. With an ImageWell control (NSImageView), bindings work directly without value the need of a transformer. A detail though, put you binding on Data binding of the view itself, not on the ImageCell objet under it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!