2009-11-01 75 views
18

我在Xcode中创建了一个静态库,我可以在其他项目中成功使用它。然而,像plists这样的资源,我发现我必须在我的图书馆中使用项目的主项目中引用任何plists。Obj-c静态库中的NSBundle,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 bundleForClass:[MyClass class]]; 

这也不能工作:

在假设[一个NSBundle mainBundle]被引用了错误的静态方法来使用,我取而代之。

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

+0

从这个问题开始赏金 - 是接受的答案仍然正确的iOS 4.2? – 2010-12-26 17:08:31

回答

17

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

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

+0

谢谢你的回答。 – Vickram 2009-11-02 15:49:16

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

下面两张截图:

  • left:带有可加载捆绑目标的静态库项目
  • right:显示添加到“Link Binary With Libraries”中的静态库二进制文件,以及添加到“Copy bundle Resources”中的资源束。

Static library project Main project

+0

hi jilouc。我坚持最后一步。 。什么是复制的资源文件? 。 plz explain – thndrkiss 2011-05-13 10:40:48

+1

@thndrkiss只需将包文件拖放到您的资源(就像您对任何其他资源文件所做的那样)并将其添加到您的项目目标。我添加了一个截图。感谢好友 – Jilouc 2011-05-13 13:59:19

+0

。 。有效 ! 。 。 – thndrkiss 2011-05-13 14:34:10

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