NSBundle的理解和mainBundle的基本介紹


一、NSBundle

  NSBundle是cocoa為bundle提供的一個類,bundle是一個目錄,其中包含了程序會使用到的資源. 這些資源包含了如圖像、聲音、編譯好的代碼、nib文件。(用戶也會把bundle稱為plug-in)

  bundle中的有些資源可以本地化。例如:對於zw.nib,我們可以有兩個版本:一個針對英語用戶,一個針對漢語用戶。在bundle中就會有兩個子目錄:English.lprojChinese.lproj,我們把各自版本的zw.nib文件放到其中。當程序需要加載zw.nib文件時,bundle會自動根據所設置的語言來加載.(在小碼哥最新的MJRefresh中就用到此方法,可以修改刷新時候的提示語言)

  獲取bundle的方法,以及簡單應用:

 

 1 - (void)viewDidLoad {
 2     [super viewDidLoad];
 3     //獲得bundle
 4     NSBundle *bundle = [NSBundle bundleWithPath:@"/Users/ZW/Desktop/abckd"];
 5     //獲取bundle文件中的圖片的路徑
 6     NSString *path = [bundle pathForResource:@"00" ofType:@"png"];
 7     //獲取圖片對象
 8     UIImage *image = [[UIImage alloc] initWithContentsOfFile:path];
 9     UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
10     [self.view addSubview:imageView];
11 }

 

  bundle還有其它用法:bundle中可以包含一個庫. 如果我們從庫得到一個class, bundle會連接庫,並查找該類,等等,以后慢慢研究

 

二、mainBundle

  我們的程序是一個bundle。 在Finder中,一個應用程序看上去和其他文件沒有什么區別。但是實際上它是一個包含了nib文件、編譯代碼以及其它資源的目錄. 我們把這個目錄叫做程序的main bundle,獲取方式如下

  NSBundle *mainBundle = [NSBundle mainBundle]; 

  應用如下:

1 - (void)viewDidLoad {
2     [super viewDidLoad];
3     NSBundle *mainBundle = [NSBundle mainBundle];
4     NSLog(@"%@",mainBundle);
5     NSString *imagePath = [mainBundle pathForResource:@"abc" ofType:@"png"];
6     UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:imagePath]];
7     [self.view addSubview:imageView];
8 }

還有其它一些用法,比如加載工具條UIToolbar *toolbar = [[[NSBundle mainBundle] loadNibNamed:@"ZWKeyboardTool" owner:self options:nil] firstObject];等等,后續還有很多實際應用

其它的一些關於NSBundle更詳細介紹可以看下博文:http://blog.sina.com.cn/s/blog_8c87ba3b0100t89v.html


免責聲明!

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



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