iOS 訪問Bundle中的資源
阿新 • • 發佈:2018-12-25
首先在專案資料夾上右擊(這是發現前面沒寫清楚,後來補的,所以專案名不一樣)
(1)新增檔案是“Add Files”
(2)新增目錄結構是“New Group”
專案的檔案目錄如下
2個圖片資原始檔均分別在mainBundle和ResourceBundle的images子資料夾中
(1)訪問mainBundle
NSString *imagePath1 = [[NSBundle mainBundle] pathForResource:@"1" ofType:@"jpg"]; UIImage *image1 = [UIImage imageWithContentsOfFile: imagePath1]; [imageview1 setImage: image1];
(2)訪問ResourceBundle
NSString *bundlePath = [[NSBundle mainBundle] pathForResource:@"other" ofType @"bundle"]; NSString *imagePath2 = [[NSBundle mainBundle] pathForResource:@"2" ofType:@"jpg" inDirectory @"images"]; UIImage *image2 = [UIImage imageWithContentsOfFile: imagePath2]; [imageview2 setImage: image2];
關鍵點總結:
(1)在mainBundle中的資源不用告訴Objective-C其所在的目錄(如果指定了inDirectory,反而無法獲取資源)
(2)在otherBundle中的資源需要顯式指定其目錄,否則無法獲取其資原始檔
原先的理解不對,應改為:如果當時新增的是資料夾則需要新增目錄;如果是直接新增檔案,則訪問時不需要新增目錄。