ObB-c静态库中的NSBundle,plist和其他资源

Vic*_*ram 19 iphone plist nsbundle

我在Xcode中创建了一个静态库,我可以在其他项目中成功使用它.但是,对于像plists这样的资源,我发现必须在我的库中引用在项目所在的主项目中引用的任何plist.

在我的静态库项目中,我的plist包含在目标的"Copy Bundle Resources"阶段.在我的代码中,这是我正在做的事情:

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

NSMutableDictionary* params = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath];
Run Code Online (Sandbox Code Playgroud)

如果我使用mainBundle并且MyClassParams.plist包含在主项目中,那么一切都很好.如果MyClassParams.plist包含在库项目中,则它不起作用.

假设[NSBundle mainBundle]引用了错误的静态方法,我将其替换为:

NSBundle *mainBundle = [NSBundle bundleForClass:[MyClass class]];
Run Code Online (Sandbox Code Playgroud)

这也不起作用.

那么,是否可以将plist或任何其他资源包含在静态库中 - 或者我是否必须在使用lib的项目中包含我需要的内容?

Lou*_*arg 18

静态库不在捆绑中,当它们链接到应用程序时,它们是该应用程序包的一部分.在iPhone上,您编写的所有代码都将在mainBundle中,因为您不能包含嵌入式框架.

所以,是的,您需要将所有资源复制到您将静态框架链接到的项目中.


Jil*_*ouc 12

我知道你不能将资源文件包含到静态库中(这就是框架所做的).我在我的项目中使用另一个解决方案

在静态库"YYY"项目中:

  • 我向我的静态库项目添加了一个"可加载包"目标(Add Target,Cocoa,Loadable Bundle)
  • 我将此目标添加为静态库目标的依赖项

在主项目内:

  • 链接 libYYY.a
  • 将捆绑包添加YYY.bundle到复制的资源文件中

这样,静态库中使用的资源文件不在主项目中进行管理.说我foo.png在静态库中有一张图片,我用

[UIImage imageNamed:@"YYY.bundle/foo.png"]
Run Code Online (Sandbox Code Playgroud)

你可以这样得到你的plist:

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

NSMutableDictionary *params = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath];
Run Code Online (Sandbox Code Playgroud)

下面是两个截图:

  • left:具有可加载bundle目标的静态库项目
  • right:显示添加到"Link Binary With Libraries"的静态库二进制文件,并将资源包添加到"Copy bundle Resources".

静态库项目 主要项目