views:

201

answers:

3

I am trying to make a simple document-based cocoa application that can save and load images in pdf files.

For the save part, I am using

- (NSData *)dataOfType:(NSString *)typeName error:(NSError **)outError
{
    return [imageView dataWithPDFInsideRect:[imageView bounds]];
}

And this works, the image could be saved to a PDF file.

For the load part, I am using

- (BOOL)readFromData:(NSData *)data ofType:(NSString *)typeName error:(NSError **)outError
{
    NSData *dataFromFile = [data retain];
    NSImage *image = [[NSImage alloc] initWithData:dataFromFile];
    NSLog(@"Load image as: %@", image);
    // Do something about the image
    if (outError != NULL) {
        NSLog(@"Error when loading data ...");
        *outError = [NSError errorWithDomain:NSOSStatusErrorDomain code:unimpErr userInfo:NULL];
        return NO;
    }
    return YES;
}

This always fails, but the NSLog prints out that the image is not NULL:

Load image as: NSImage 0x16ead890 Size={1023, 601} Reps=(NSPDFImageRep 0x16e97480 Size={1023, 601} ColorSpace=NSCalibrateRGBColorSpace BPS=0 Pixels=1023x601 Alpha=NO)

Error when loading data ...

I don't quite understand what problem happens in the readFromData that makes outError != NULL here.

A: 

You're passing outError from whatever is calling -readFromData:ofType:error:. What's more, outError is a pointer-to-a-pointer. What you should check is:

if (outError != nil && *outError != nil) {...
Ben Gottlieb
It doesn't work even after remove the whole "if (outError != NULL)" part. The previously saved pdf image is loaded as empty image.
ccy
+1  A: 

Your image is being successfully created.

You're not quite understanding how the error parameter works. Your -readFromData:ofType:error: method is handed a pointer to a pointer, for you to use if you fail at creating the image from the NSData instance.

You should read the documentation on NSError to get your head around how to create and use NSError instances.

NSResponder
Better yet, the Error Handling Programming Guide for Cocoa: http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/ErrorHandlingCocoa/ Particularly the “Using and Creating Error Objects” section.
Peter Hosey
A: 

outError is there for you to set if you have an error reading the document. It doesn't tell you whether your code failed or not. It's how you tell the caller what went wrong. [NSImage initWithData:] returns nil if it fails, so you need to change:

if (outError != NULL) {

to:

if (image == NULL) {
Dewayne Christensen