2009-11-01 72 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];