Bundle文件的創建和使用


轉自:https://www.cnblogs.com/cy568searchx/p/4682843.html

經常會出現某個需求:將自己的模塊或者開放類,封裝成靜態庫給其他人提供方便的調用。

但是當你的模塊中需要大量使用xib,圖片,音頻或者其他資源文件時,無法添加至靜態庫。這個時候就需要將一些資源文件封裝至.Bundle文件中。那么封裝好的東西應該含有三類文件:

1:開放的頭文件(包含完整的調用注釋)

2:靜態庫文件 后綴名為.a

3:Bundle文件,用於存放各種資源文件。

 那么其他的都很簡單:這里具體說說bundle文件的封裝(其實也很簡單)

第一步:創建Bundle項目

選擇Bundle文件類型后並創建項目。

 第二步:修改BuildSetting相關設置

1:Base SDK 修改為 iOS6 或者其他存在的iOS SDK版本

2:Architectures   修改為 armv7 armv7s

 

 

 

第三步:添加需要添加的資源文件

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

第四步:Build (這里不需要使用證書也可以編譯成功)

 

 



這樣就生成了自己的Bundle

 

調用的時候助需要引用至項目中就行,如下:

程序中引入方式:

獲得bundle中的資源

NSString * bundlePath = [[ NSBundle mainBundle] pathForResource: @ "MyBundle" ofType :@ "bundle"];
NSBundle *resourceBundle = [NSBundle bundleWithPath:bundlePath];
UIViewController *vc = [[UIViewController alloc] initWithNibName:@"vc_name" bundle:resourceBundle];

圖片獲得bundle中的資源

UIImageView *imgView=[[UIImageView alloc] initWithFrame:CGRectMake(50, 50, 50, 50)];
UIImage *image = [UIImage imageNamed:@"MyBundle.bundle/img_collect_success"];
[imgView setImage:image];

或者

UIImageView *imgView=[[UIImageView alloc] initWithFrame:CGRectMake(50, 50, 50, 50)];
NSString *imgPath= [bundlePath stringByAppendingPathComponent :@"img_collect_success.png"];
UIImage *image_1=[UIImage imageWithContentsOfFile:imgPath];
[imgView setImage:image_1];

當然,可以寫成預編譯語句:
#define MYBUNDLE_NAME @ "MyBundle.bundle"
#define MYBUNDLE_PATH [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent: MYBUNDLE_NAME]
#define MYBUNDLE [NSBundle bundleWithPath: MYBUNDLE_PATH]

 

如果想要將在某個非mainBundle的地方調用。那么需要額外加載此Bundle


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM