Search code examples
cocoamacosnsimagensbundle

Cocoa - problem with this code using NSBundle


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?


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