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

做~自己de王妃 提交于 2019-11-29 20:29:31

Static Libraries are not in bundles, when they get linked into an application they are part of that applications bundle. On the iPhone, effectively all code you write will be in the mainBundle since you can't include embedded frameworks.

So yes, you need to copy over all the resources into the project you are linking the static framework into.

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".

efinal

I followed everything @Jilouc suggested, however, I can get the bundle but failed to get files inside it. I tried both the two ways (@"yyy.bundle/image" or staticlib pathforresource...)

Then I used the method below and it worked!

NSBundle *staticBundle = [NSBundle bundleWithPath:[[[NSBundle mainBundle]resourcePath] stringByAppendingPathComponent:@"yy.bundle"]];

NSString *filePath = [[jsBundle resourcePath]stringByAppendingPathComponent:fileName];

NSString* content = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:NULL];
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!