0

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?

Abizern
  • 146,289
  • 39
  • 203
  • 257
Brian
  • 63
  • 6

2 Answers2

5

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
  • 25,520
  • 5
  • 61
  • 71
4

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
  • 95,783
  • 15
  • 211
  • 370