Question

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?

Was it helpful?

Solution

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"];

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top