views:

292

answers:

2

It was suggested that I use this line of code to call an image from my resources folder/project bundle. I also see it being used exactly like this on many different website tutorials.

NSBundle *mb=[NSBundle mainBundle];


NSString *fp=[mb pathForResource:@"topimage" ofType:@"PNG"];


NSImage *image=[NSImage initWithContentsOfFile:fp];

HOWEVER, I am receiving the following warning:

NSImage may not respond to +initWithContentsOfFile+

The documentation for NSImage shows that initWithContentsOfFile is in fact a method that should work. What might I be missing here?

+5  A: 

You're missing an +alloc

NSImage* image = [[NSImage alloc] initWithContentsOfFile:fp];

You can also use +imageNamed:, which fetches images from your main bundle.

NSImage* image = [NSImage imageNamed:@"topImage.png"];
Darren
Thanks! Exactly what the issue was
Brian
+3  A: 

initWithContentsOfFile: is an instance method, but you're sending that message to the NSImage class. You need to send it to an instance—specifically, a freshly-allocated instance.

That's where alloc comes in. It's a class method that allocates an instance, which you then immediately send the init… message (as Darren showed).

Don't forget to release the instance when you're done with it. I generally autorelease the instance immediately after initing it; then, Cocoa will release the instance for me at an appropriate time. See the Memory Management Programming Guide for Cocoa for more information.

Peter Hosey