Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way to load an image from a framework in OS X Yosemite (10.10)?

I'm working on a Yosemite app that includes a Notification Center widget (or Today extension). I have a framework where I'm storing all of my shared code and resources, which includes some images. Whether I just use PNGs or an asset catalog, they don't load if I just use the standard NSImage method imageNamed:. Looking at the documentation, that's clearly expected—it only looks in the main bundle.

On iOS, UIImage has a new method, imageNamed:inBundle:compatibleWithTraitCollection: that's perfeclty suited to this problem. I don't see anything similar for NSImage.

It seems like the best option is to do something like this:

[[NSBundle bundleForClass:[self class]] imageForResource:@"name"];

The main problem with this is that it doesn't use caching. In order to do that I added my own method in a category:

+ (NSImage *)imageNamed:(NSString *)name inBundle:(NSBundle *)bundle {
    NSImage *image = [NSImage imageNamed:name];
    if (image == nil) {
        image = [bundle imageForResource:name];
        [image setName:name];
    }
    return image;
}

This seems okay, but is there a better solution?

like image 850
robotspacer Avatar asked Aug 02 '14 03:08

robotspacer


1 Answers

There isn't currently API to do this in one method call, but I just filed radar://25632204 to request that +[NSImage imageNamed:inBundle:] be added for parity with UIKit.

like image 127
Quinn Taylor Avatar answered Dec 06 '22 15:12

Quinn Taylor