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

posted @ 2016-08-23 10:23  _水畔竹汐  阅读(4692)  评论(0编辑  收藏  举报