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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With