4

I am trying put an image in a view. This is my code:

NSImageView *imView = [[NSImageView alloc] initWithFrame:NSMakeRect(0, 0, 480, 360)];
    NSImage *myImage = [[NSImage alloc] initByReferencingFile:@"image.png"];
    [imView setImage:myImage];
    [theView addSubview:imView];
    [window setContentView:theView];

But the window is blank(image doesn't get drawn). If I place a textfield in the view for example.. it works perfectly, but not NSImageView...I checked the console and there's no warning/error messages... Thanks!

user635064
  • 6,219
  • 12
  • 54
  • 100
  • 1
    Check whether `myImage` is valid: `NSLog(@"image is valid? %@", [imView isValid] ? @"yes" : @"no");` –  Apr 11 '11 at 04:56
  • 1
    Also, you’re leaking both `imView` and `myImage` in this code snippet. –  Apr 11 '11 at 04:57
  • Thanks for the input. You're right, its not valid. What could be wrong? Thanks again. – user635064 Apr 11 '11 at 04:59
  • Yes, i know about the leaks, I am merely trying to learn how to put image in an nsview i can careless about the memory right now its a dummy project i created just to test...thanks though. – user635064 Apr 11 '11 at 05:00
  • 2
    Most likely Cocoa is not finding that file. Try using `+imageNamed:` instead. Where is that file located? –  Apr 11 '11 at 05:01
  • Inside my project folder, in xcode i can see it in my Resources folder. – user635064 Apr 11 '11 at 05:02
  • Oh, +imageNamed: worked! Thanks man! Still would like to know what was wrong with initbyReferencingFile.. – user635064 Apr 11 '11 at 05:04

1 Answers1

9

Since [imView isValid] returns false, this means that NSImage hasn’t been able to create an image based on that file. A common reason is that the file couldn’t been located. From the documentation of -initByReferencingFile:,

filename A full or relative path name specifying the file with the desired image data. Relative paths must be relative to the current working directory.

This means that the behaviour of -initByReferencingFile: depends on the current directory, and ideally you should pass the full path name.

A better solution is to use +imageNamed: instead because of two reasons: it uses an image cache and it is able to look for a file inside the application bundle.