NSBundle介紹及使用


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

cocoa提供了類NSBundle.

 

bundle 文件的創建,只需要在本地創建一個文件夾,給文件夾添加后綴@".bundle"

 

那么在工程中獲取這個 bundle 文件夾的路徑我們使用 

   [[NSBundle mainBundle] pathForResource:<#(nullable NSString *)#> ofType:<#(nullable NSString *)#>] 是獲取不到路徑的

 

如果是在工程文件下我們使用

    //例 NSURL *fileURl = [[NSBundle mainBundle] URLForResource:@"books" withExtension:@"epub"];

 

在bundlle文件夾下我們需要使用

[NSBundle mainBundle]resourcePath]

    //[NSBundle mainBundle]是獲得NSBundle的一個單例對象,次單例對象 已經設置了默認的resourcePath,也就是你的app打包后的路徑,[NSBundle    mainBundle]resourcePath]就是獲得這個完整的打包后的app路徑,但你的books.txt文件並不在這個目錄,而是在app內部,這時就需要拼接路徑字符串[NSString stringWithFormat:@"%@%@%@",[[NSBundle mainBundle]resourcePath],@"/",path];

    //在 bundle 文件下需要使用這種方法,但是中文的 URL 必須 UTF8編碼

    NSString *file = [NSString stringWithFormat:@"file://%@/books.epub",[[NSBundle mainBundle]resourcePath]];

    //NSString *encoding = [file stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

    NSURL *fileURl = [NSURL URLWithString:file];

 

控制台輸出

 

file:///Users/apple/Library/Developer/CoreSimulator/Devices/9787BF52-ACE1-4A9F-9A8D-7BF6D6E7AC82/data/Containers/Bundle/Application/07B97638-C045-4DAC-9F82-B2219A28AE9E/EPUBBooks.app/books.epub


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM