NSBundle, plist and other resources in an Obj-c Static Library

Viewed 11001

I've created a static library in Xcode, which I am able to successfully use in other projects. However, with resources like plists, I find I must include any plists referenced in my library in the main project where the project is used.

In my static library project, I have my plist included in the "Copy Bundle Resources" phase of the target. In my code, here is what I am doing:

NSBundle *mainBundle = [NSBundle mainBundle];
NSString *filePath   = [mainBundle pathForResource:@"MyClassParams" ofType:@"plist"];

NSMutableDictionary* params = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath];

If I use mainBundle and the MyClassParams.plist is included in the main project, all is good. If MyClassParams.plist is included in the library project, it doesn't work.

On the assumption that [NSBundle mainBundle] was referencing the wrong static method to use, I replaced it with:

NSBundle *mainBundle = [NSBundle bundleForClass:[MyClass class]];

This did not work either.

So, is it possible to include a plist or any other resources with a static library -- or do I have to include whatever I need in the project where the lib is used?

3 Answers

I know you can't include resource files into a static library (that's what frameworks do). I use another solution in my projects:

Inside the static library "YYY" project:

  • I add a "Loadable Bundle" target to my static library project (Add Target, Cocoa, Loadable Bundle)
  • I add this target as a dependency of the static library target

Inside the main project:

  • Link the libYYY.a
  • Add the bundle YYY.bundle to the copied resource files

This way, resource files used in the static library are not managed in the main project. Say I have a foo.png picture in the static library, I use

[UIImage imageNamed:@"YYY.bundle/foo.png"]

You could then get your plist like this:

NSBundle *staticLibBundle = [NSBundle bundleWithPath:[[NSBundle mainBundle] pathForResource:@"YYY" ofType:@"bundle"]];
NSString *filePath   = [staticLibBundle pathForResource:@"MyClassParams" ofType:@"plist"];

NSMutableDictionary *params = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath];

Below, two screenshots:

  • left: static library project with loadable bundle target
  • right: showing the static library binary added to "Link Binary With Libraries" and the resource bundle added to "Copy bundle Resources".

Static library project Main project

Related