How to build and use multiple resource bundles in an iOS project
Question: I am building iOS 4.2 applications with some common methods in a static library. This has been working quite well, but I am getting messing up my projects. I cannot manage well my common image and data files which the static library would like to use in the apps. I’m getting close to needing to deploy the applications, so I decided to try to package the resources into a dedicated bundle. This custom bundle will be added to my projects. I googled for examples but have not found the answer on how to get these resource files from my own bundle in runtime.
Answer: There are several good reasons to build an application with multiple bundles and several different ways to do it. To my experience the best way is open Xcode and create a new bundle project:
1. Select: File -> New Project… -> Group Mac OSX (!) -> Framework & Library -> Bundle. Add your resource files to the project.
2. Build the bundle as you build other iPhone apps.
3. You may add this project to your static library project and rebuild it all the time the library is changed. You must know that the bundle itself will not be linked to your library file.
4. In your app projects add the .bundle file to your project as an ordinary resource file (Add -> Existing Files… -> find and select the above built .bundle file. Do not copy it).
Examples:
iOS NSBundle class reference
Loading bundles
#define MYBUNDLE_NAME @"MyResources.bundle"
#define MYBUNDLE_IDENTIFIER @"eu.oaktree-ce.MyResources"
#define MYBUNDLE_PATH [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent: MYBUNDLE_NAME]
#define MYBUNDLE [NSBundle bundleWithPath: MYBUNDLE_PATH]
// Get an image file from your "static library" bundle:
- (NSString *) getMyBundlePathFor: (NSString *) filename
{
NSBundle *libBundle = MYBUNDLE;
if( libBundle && filename ){
return [[libBundle resourcePath] stringByAppendingPathComponent: filename];
}
return nil;
}
// .....
// Get an image file named info.png from the custom bundle
UIImage *imageFromMyBundle = [UIImage imageWithContentsOfFile: [self getMyBundlePathFor: @"info.png"] ];