Add an image (or other resources) to a Mac or iOS Framework
Let's say I have an existing iOS or Mac Framework that we'll call Test.framework. This framework has compiled and linked successfully (a trick was done to lipo both i386 and armv6/7 archs for the iOS part) and is working perfectly fine.
Now I want to add an image to it let's call it 'test.png
'. I have copied it into the Resources folder of my framework so that I have the following structure:
ls Test.framework
- Headers -> Versions/Current/Headers
- Resources -> Versions/Current/Resources
- Test -> Versions/Current/Test
- Versions
ls Test.framework/Resources
- Info.plist
- test.png
Yet when I create a project using my framework I cannot access that image.
I've tried:
[UIImage imageNamed:@"test.png"]
[UIImage imageNamed:@"Test.framework/test.png"]
[UIImage imageNamed:@"Test.framework/Resources/test.png"]
But nothing worked out that always gave me back a nil
object.
Any ideas ?
EDIT
After much further investigation it seems what I am trying to accomplish can't be done on iOS. The reason is that the final application bundle (the .app) doesn't copy the private frameworks where applications compiled for Mac OS will.
This is further detailed in the iOS Bundle Structures documentation.
Thanks to Rob Keniger and xuzhe for their appreciated help. I will credit xuzhe for the answer as it is actually the most appropriate answer to my origin开发者_开发百科al problem (even though Rob comment made me dig quite deeper into the issue)
The "imageNamed:" method is only for images in your App bundle. You should use
[[UIImage alloc] initWithContentsOfFile:path];
instead.
About the path, since I am not sure if the "Test.Framework" is in you App bundle, I am not able to give you a sample code. But if it dose, the code below should work:
NSString* path = [Nsstring stringWithFormat:@"%@/Test.framework/Resources/test.png", [[NSBundle mainBundle] bundlePath]];
You can get the bundle for a particular class using [NSBundle bundleForClass:[SomeClass class]]
. All you need to do is pass in a class that's defined in the framework and you'll have a reference to the framework's bundle.
You can then ask the bundle for the path to the image using the pathForResource:ofType:
method of NSBundle
, and then use the initWithContentsOfFile:
method of NSImage
to create your image.
Note that you should never hard-code paths. Ever. There are many different functions and methods for obtaining paths to resources, you never need to hard-code them.
精彩评论