Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

GregX999

macrumors newbie
Original poster
Apr 5, 2009
18
0
Hey, stupid newbie question here...

I'm trying to load an image from the Resources folder using initWithContentsOfFile. The code below always writes "Invalid Image" in the log. (And looking at the NSImage object in the debugger shows the "_name" as "Invalid".)

Code:
image = [[NSImage alloc] initWithContentsOfFile:@"player_ship.png"];

if (![image isValid]) {
	NSLog(@"Invalid Image");
}

I copied that file into the Resources folder in xCode, and if "View Package Contents" of the build, it's in the Resources folder there too. It's just a png file I saved via Photoshop's "Save for Web" function.

Is there anyway I can figure out what the problem is?

Thanks,
Greg
 

kainjow

Moderator emeritus
Jun 15, 2000
7,958
7
File paths in Cocoa must be absolute, and you're passing a relative path. To get the absolute path of a file in your app's Resources folder, you need to use the NSBundle class. Look at the docs, it should be fairly obvious.
 

lee1210

macrumors 68040
Jan 10, 2005
3,182
3
Dallas, TX
I would encourage looking this stuff up on your own as well, but since i already went to the trouble i figured i'd post what i found. You'll have to verify, i haven't tried compiling this or anything.
Code:
NSString *myImagePath = [[[NSBundle mainBundle] resourcePath]  stringByAppendingString:@"player_ship.png"];
NSImage *myImage = [[NSImage alloc] initWithContentsOfFile:myImagePath];

Relevant links:
NSBundle
http://developer.apple.com/DOCUMENT...asses/NSBundle_Class/Reference/Reference.html

NSString
http://developer.apple.com/document...lasses/NSString_Class/Reference/NSString.html

-Lee
 

GregX999

macrumors newbie
Original poster
Apr 5, 2009
18
0
Thanks guys! I wasn't even aware of NSBundle. It would be kind of nice if the docs for initWithContentsOfFile at least mentioned it.

Lee, your code worked except for a missing "/". It needed to be:
stringByAppendingString:mad:"/player_ship.png"

Greg
 

lee1210

macrumors 68040
Jan 10, 2005
3,182
3
Dallas, TX
Ah, right. Might be better to use NSString's:
stringByAppendingPathComponent:

That will ensure the / is there:
Code:
NSString *myImagePath = [[[NSBundle mainBundle] resourcePath]  stringByAppendingPathComponent:@"player_ship.png"];

-Lee
 

kainjow

Moderator emeritus
Jun 15, 2000
7,958
7
There's also the handy pathForImageResource: method when dealing with images.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.