开发者

NSImage readFromData problem

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 开发者_如何学Cfile.

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.


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.


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) {...


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) {
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜