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

时间:2009-11-01 16:35:45

标签: 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];

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

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

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

这也不起作用。

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

3 个答案:

答案 0 :(得分:18)

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

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

答案 1 :(得分:12)

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

在静态库“YYY”项目中:

  • 我将“可加载捆绑”目标添加到我的静态库项目(添加目标,可可,可加载捆绑包)
  • 我将此目标添加为静态库目标
  • 的依赖项

主项目内:

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

这样,静态库中使用的资源文件不在主项目中管理。假设我在静态库中有foo.png图片,我使用

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

然后你可以这样得到你的plist:

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

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

下面有两个截图:

  • :具有可加载捆绑目标的静态库项目
  • 正确:显示静态库二进制文件已添加到“Link Binary With Libraries”并且资源包已添加到“Copy bundle Resources”。

Static library project Main project

答案 2 :(得分:2)

我遵循@Jilouc建议的所有内容,但是,我可以获得捆绑但无法获取文件。我尝试了两种方式(@"yyy.bundle/image"staticlib pathforresource...

然后我使用下面的方法,它有效!

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];