1. 程式人生 > >IOS開發NSBundle物件使用詳解

IOS開發NSBundle物件使用詳解

bundle是一個目錄,其中包含了程式會使用到的資源. 這些資源包含了如影象,聲音,編譯好的程式碼,nib檔案(使用者也會把bundle稱為plug-in). 對應bundle,cocoa提供了類NSBundle.

我們的程式是一個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

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

獲取屬性列表
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"ViewControllers" ofType:@"plist"]];