19

我在 Xcode 中创建了一个静态库,我可以在其他项目中成功使用它。但是,对于 plist 之类的资源,我发现我必须在使用该项目的主项目中包含我的库中引用的任何 plist。

在我的静态库项目中,我的 plist 包含在目标的“复制捆绑资源”阶段。在我的代码中,这就是我正在做的事情:

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 的项目中包含我需要的任何内容?

4

3 回答 3

18

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

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

于 2009-11-02T02:06:41.690 回答
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”的资源包。

静态库项目 主要项目

于 2010-12-27T14:37:57.130 回答
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];
于 2011-07-23T08:41:45.187 回答