7

I am playing with AppKit and NSDocument and I don't know why this is not working?:

I just wrote this and image is not nil but never loads any image, its size is always zero. Is this the correct method I have to implement to read files into my document? I need the path, not the data (NSData) because I plan to use other library to read other files.

Now I am trying to read PNGs, JPGs , none worked. ;(

- (BOOL) readFromURL:(NSURL *)url ofType:(NSString *)typeName error:(NSError **)outError{

    NSImage *image = nil;
    image = [[NSImage alloc] initWithContentsOfURL:url];

    [imageView setImage:image];
    [image release];

    if ( outError != NULL ) {
        *outError = [NSError errorWithDomain:NSOSStatusErrorDomain code:unimpErr userInfo:NULL];
    }
    return YES;
}

Thanks in advance.

nacho4d
  • 43,720
  • 45
  • 157
  • 240

2 Answers2

8

Do it this way:

NSImage *image = [[NSImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:url]]];
Matt S.
  • 13,305
  • 15
  • 73
  • 129
6

If imageView is being loaded from a NIB file, it will not have been set when readFromURL:ofType:error: is called. Instead, you should load the image and store it in an instance variable, then add it to the imageView in the windowControllerDidLoadNib: method. Also, you are returning an error every time, while you should only return an error if something goes wrong.

- (void)windowControllerDidLoadNib:(NSWindowController *)windowController {
    [imageView setImage:image];
    [image release];
    image = nil;
}
- (BOOL)readFromURL:(NSURL *)url ofType:(NSString *)typeName error:(NSError **)outError {
    image = [[NSImage alloc] initWithContentsOfURL:url];
    if(!image) {
        if(outError) *outError = [NSError errorWithDomain:NSOSStatusErrorDomain code:unimpErr userInfo:NULL];
        return NO;
    }
    return YES;
}

Just make sure you add a NSImage *image; instance variable to your header file.

ughoavgfhw
  • 39,734
  • 6
  • 101
  • 123
  • 1
    Great answer. The "unimpErr" placeholder error equates to "Unimplemented error", which is there really just in case the developer hasn't fleshed out that method yet. In the case of loading an image which fails, it'd probably make more sense to use one of Cocoa's NSFileCorrupt codes (sorry, not sure of the exact enum name). – NSGod Dec 15 '10 at 21:34