Question

I have JSON that contains base64 decoded PNG-images that I add to Core Data. I would like to show those images in Image Wells with bindings to my Core Data model.

The problem is that I cannot use Data with NSArchiveFromData since it's been deprecated.

My problem is similar to this but I don't really understand the answer.

Does anyone have an idea?

Thanks

Was it helpful?

Solution

Try something to the effect of this (I'm not sure if you're just using a binding on a property, or using an NSArrayController - I'll try to answer both scenarios)

You could take the string from your json and decode it: (You'll need the open source library referenced in the stackoverflow answer: https://stackoverflow.com/questions/14260936/decode-an-encoded-base64-image-in-c-sharp-in-objective-c)

NSString *jsonImage = [jsonData objectForKey@"image"];
NSData   *data      = [NSData dataWithBase64EncodedString:jsonImage];

Then init your image with that data.

If you're using an NSArrayController to manage your core data, create a value transformer that returns an image.

Create a subclass of NSValueTransformer and name it whatever you'd like. In the implementation, add:

+(Class)transformedValueClass {
    return [NSImage class];
}
-(id)transformedValue:(id)value {
    if (value == nil) {
        return nil;
    } else {
        NSData *data = [NSData dataWithBase64EncodedString:value]; //might be [value stringValue]
        return [[NSImage alloc] initWithData:data];
    }
}

Then in interface builder where you've set the binding on the image, just set the Value Transformer to the class you made.

OTHER TIPS

You didn't define what exactly is your problem.

To load NSImage from NSData see Apple docs and initWithData:.


Let's say You have such core data object:

@class MyObject : NSManagedObject

@property NSData *imageData;

@end 

and it's implementation:

@implementation MyObject

@dynamic imageData; 

@end

Now, add to it a new property:

-(NSImage *)bindableImage {
    [self willAccessValueForKey:@"bindableImage"];
    NSImage *myImage = [[NSImage alloc] initWithData:[self imageData]];
    [self didAccessValueForKey:@"bindableImage"];
    return myImage;
}

also, inform bindings what changes when imageData property has been changed:

+ (NSSet *)keyPathsForValuesAffectingImageData {
    return [NSSet setWithObjects:@"bindableImage", nil];
}

That's it. I think, it should work, but I didn't try :)


I forgot about Base64 - check another answer.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top