Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSURL → NSImage → NSImageView

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.

like image 899
nacho4d Avatar asked Dec 15 '10 18:12

nacho4d


2 Answers

Do it this way:

NSImage *image = [[NSImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:url]]];
like image 131
Matt S. Avatar answered Nov 16 '22 08:11

Matt S.


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.

like image 38
ughoavgfhw Avatar answered Nov 16 '22 07:11

ughoavgfhw