views:

34

answers:

1

Just started exploring Cocoa so pretty much a total noob.

I've written a very simple game. Set it up in Interface Builder and got it working fine.

It contains a number of buttons and I'm now trying to get the buttons to display images.

To start with I'm trying to get an image displayed on just one of the buttons which is called tile0 .

The image file (it's nothing but a green square at the moment, but I'm just trying to get that working before I attempt anything more exotic) is sitting in the same directory as the class file which controls the game.

I have the following code sitting in my wakeFromNib method:

 NSString *myImageFileName = [[NSString alloc] init];
 myImageFileName = @"greenImage.jpg";
 NSImage *myImage = [[NSImage alloc] initByReferencingFile:myImageFileName];
 [tile0 setImage: myImage];

Trouble is, the game runs fine, but the image isn't appearing on my button.

Is there someone who could kindly tell me if I'm doing something obviously wrong?

Many Thanks.

+1  A: 

The first problem is you allocate a string but then replace it with a string constant. That isn't causing your image problem but it is a memory leak.

I've never used initByReferencingFile, I usually just use imageNamed:. There is an example of using imageNamed here.

progrmr
And if you do use imageNamed:, you need to put the image in your app's Resources directory. You can't just put images next to the source and expect the binary to find it.
JWWalker
Excellent. imageNamed worked fine.Many thanks for your help. Much appreciated.I have books, and I use the docs as much as possible but sometimes asking others is the only thing to do :-)
A Mann
The reason why `initByReferencingFile:` doesn't work is that `initByReferencingFile:`, like its cousin `initWithContentsOfFile:`, takes a pathname. You passed a filename, which works as a relative path, but this didn't work because there is no such file in the current working directory (which defaults to the root of the file-system—i.e., there is no /greenImage.jpg). `imageNamed:` works because (a) it specifically wants a filename (with or without extension) and (b) it looks for the file with that name in loaded bundles' Resources directories, not the current working directory.
Peter Hosey
Thanks, Peter. That's helpful, especially as I'm now starting to look at some very basic graphics, and drawing images into rectangles, using imageNamed. Appreciate your help.
A Mann