iOS開發bundle物件使用詳解

2021-07-10 10:06:10 字數 1667 閱讀 5402

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];

一旦我們有了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"]];

Bundle物件的使用

在android開發中,如果要通過乙個activity啟動另外乙個activity,需要呼叫startactivity 函式,這個函式的引數是乙個intent物件,這個物件通常的初始化方式如下 intent intent new intent intent.setclass this,seconda...

iOS開發裡的Bundle是什麼

bundle簡單地講,就是乙個內部結構按照標準規則組織的特殊目錄 現在我們已經知道了,原來我們開發的應用程式,最後都會成為乙個bundle,那麼就不難理解為什麼很多資源檔案載入大多是通過bundle來進行的了,從bundle進行檔案載入實際就是通過應用自己所在的資料夾進行載入。不過緊接著我們又會產生...

IOS開發NSBundle物件使用詳解

bundle是乙個目錄,其中包含了程式會使用到的資源.這些資源包含了如影象,聲音,編譯好的 nib檔案 使用者也會把bundle稱為plug in 對應bundle,cocoa提供了類nsbundle.我們的程式是乙個bundle.在finder中,乙個應用程式看上去和其他檔案沒有什麼區別.但是實際...