IOS開發NSBundle對象使用詳解

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

咱們的程序是一個bundle. 在Finder中,一個應用程序看上去和其餘文件沒有什麼區別. 可是實際上它是一個包含了nib文件,編譯代碼,以及其餘資源的目錄. 咱們把這個目錄叫作程序的main bundle 對象

bundle中的有些資源能夠本地化.例如,對於foo.nib,咱們能夠有兩個版本: 一個針對英語用戶,一個針對法語用戶. 在bundle中就會有兩個子目錄:English.lproj和French.lproj,咱們把各自版本的foo.nib文件放到其中. 當程序須要加載foo.nib文件時,bundle會自動根據所設置的語言來加載. 咱們會在16章再詳細討論本地化
經過使用下面的方法獲得程序的main bundle
NSBundle *myBundle = [NSBundle mainBundle];
通常咱們經過這種方法來獲得bundle.若是你須要其餘目錄的資源,能夠指定路徑來取得bundle
NSBundle *goodBundle;
goodBundle = [NSBundle bundleWithPath:@"~/.myApp/Good.bundle"];
一旦咱們有了NSBundle 對象,那麼就能夠訪問其中的資源了
// Extension is optional
NSString *path = [goodBundle pathForImageResource:@"Mom"];
NSImage *momPhoto = [[NSImage alloc] initWithContentsOfFile:path];
bundle中能夠包含一個庫. 若是咱們從庫獲得一個class, bundle會鏈接庫,並查找該類:
Class newClass = [goodBundle classNamed:@"Rover"];
id newInstance = [[newClass alloc] init];
若是不知到class名,也能夠經過查找主要類來取得
Class aClass = [goodBundle principalClass];
id anInstance = [[aClass alloc] init];
能夠看到, NSBundle有不少的用途.在這章中, NSBundle負責(在後臺)加載nib文件. 咱們也能夠不經過NSWindowController來加載nib文件, 直接使用NSBundle:
BOOL successful = [NSBundle loadNibNamed:@"About" owner:someObject];
注意噢, 咱們指定了一個對象someObject做爲nib的File」s Owner ip

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

獲取屬性列表 NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"ViewControllers" ofType:@"plist"]];
相關文章
相關標籤/搜索