NSBundle--獲取文件路徑


         之前在初始化一個類的時候:TestViewController *viewcontroller=[[TestViewController alloc]initWithNibName:@"TestViewController" bundle:[NSBundle mainBundle]];不是很明白:[NSBundle mainBundle]的意思。後來查閱資料後知道了它的作用,如下:

         bundle是一個目錄,其中包含了程序會使用到的資源. 這些資源包含了如圖像,聲音,編譯好的代碼,nib文件(用戶也會把bundle稱爲plug-in). 對應bundle,cocoa提供了類NSBundle.我們的程序是一個bundle. 在Finder中,一個應用程序看上去和其他文件沒有什麼區別. 但是實際上它是一個包含了nib文件,編譯代碼,以及其他資源的目錄. 我們把這個目錄叫做程序的main bundle。

通過使用下面的方法得到程序的main bundle
NSBundle *myBundle = [NSBundle mainBundle];

一般我們通過這種方法來得到bundle.如果你需要其他目錄的資源,可以指定路徑來取得bundle
NSBundle *goodBundle;
goodBundle = [NSBundle bundleWithPath:@"~/.myApp/Good.bundle"];

一旦我們有了NSBundle 對象,那麼就可以訪問其中的資源了

NSBundle束,是一種特定的文件類型,其中的內容遵循特定的結構。

NSBundle的一個主要作用是 獲取Resources文件夾中的資源

 

        在編程中使用[NSData dataWithContentOfFile:@"foo"]的時候,總是無法讀取正確的文件內容。而使用[NSData dataWithContentOfFile:[[NSBundle mainBundle] pathForResource:@”foo” ofType:@”"]的時候就可以。

因爲當使用相對路徑的時候,其實他相對的當前目錄並不是程序運行的目錄,而是“/”。只有使用[NSBundle mainBundle]來生成的路徑纔是文件真正的路徑。

在此記錄一下:在以後的開發中不直接使用任何相對路徑,而是使用經過計算以後的絕對路徑
 

一.獲取圖片

  1.   NSString *path = [[NSBuddle mainBuddle] pathForResource:@"resourceName" oftype@"resourceType"];

       UIImage *image = [[UIImage imageWithContentsOfFile:path];

  2.   UIImage *image = [UIImage imageNamed:@"imageName"];

二.獲取plist文件

  NSArray *array =[[NSArrayalloc]initWithContentsOfFile:[[NSBundlemainBundle]pathForResource:@"name"ofType:@"plist"]];

  NSDictionary *dict=[arrayobjectAtIndex:index];//將plist文件中的內容轉換成字典

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章