IOS 之 NSBundle 使用

IOS開發的時候,常常看到這樣的代碼, ios

[[NSBundle mainBundle] pathForResource:@"someFileName" ofType:@"yourFileExtension"];  google

[YourViewController initWithNibName:"YourViewController" bundle:nil]; xml

一開始還不是很理解,經過google,慢慢的知道bundle在ios中的做用。 對象

Bundle是什麼呢?bundle是一個目錄,其中包含了程序會使用到的資源. 這些資源包含了如圖像,聲音,編譯好的代碼,nib文件(用戶也會把bundle稱爲plug-in). 對應bundle,cocoa提供了類NSBundle.bundle中的有些資源能夠本地化.例如,對於foo.nib,咱們能夠有兩個版本: 一個針對英語用戶,一個針對法語用戶. 在bundle中就會有兩個子目錄:English.lproj和French.lproj,咱們把各自版本的foo.nib文件放到其中. 當程序須要加載foo.nib文件時,bundle會自動根據所設置的語言來加載. ip

//在程序中得到main bundle ci

NSBundle bundle = [NSBundle mainBundle];  //很簡單 資源

//通常咱們經過這種方法來獲得bundle.若是你須要其餘目錄的資源,能夠指定路徑來取得bundle 開發

NSBundle otherBundle = [NSBundle bundleWithPath:@"~/.myApp/Good.bundle"]; it

//一旦咱們有了bundle,就能夠訪問其中的資源文件了。 io

NSString path = [otherBundle pathForImageResource:@"img"];

NSImage img = [[NSImage alloc] initWithContentsOfFile:path];

//bundle中能夠包含一個庫. 若是咱們從庫獲得一個class, bundle會鏈接庫,並查找該類:

Class newClass = [otherBundle classNamed:@"Person"];

id person = [[newClass alloc] init];

//若是不知到class名,也能夠經過查找主要類來取得

Class aClass = [otherBundle principalClass];

id classInstance = [[aClass alloc] init];

//能夠看到, NSBundle有不少的用途.在這章中, NSBundle負責(在後臺)加載nib文件. 咱們也能夠不經過NSWindowController來加載nib文件, 直接使用NSBundle:

BOOL flag = [NSBundle loadNibNamed:@"ViewController" owner:someObject];

//注意噢, 咱們指定了一個對象someObject做爲nib的File」s Owner

 

獲取XML文件 NSString *filePath = [[NSBundle mainBundle] pathForResouse:@"re" ofType:@"xml"]; NSData *data = [[NSData alloc] initWithContentsOfFile:filePath];

相關文章
相關標籤/搜索