【iOS 开发】将图片、声音等资源文件打包为 Bundle 的方
2017-06-05 本文已影响109人
爱吃鸭梨的猫

最近在将项目部分代码打包成
Framework
的时候,需要将其中的图片等资源文件打包为Bundle
来使用,所以简单的了解了一下,事实上Bundle
就是一个普通得不能再普通的文件夹, 只是加上了.bundle
后缀而已,下面分享一下打包及使用方法。
1. 创建 Bundle 文件
创建 Bundle
文件有两种方法,是没有区别的,用哪种方法自己选择。
- 一种是在项目中按下
command + N
,或者右键项目文件夹点击New File
,选择iOS
-Resource
-Settings Bundle
。

- 另一种是在项目根目录创建一个文件夹,然后重命名文件夹为
xxx.bundle
,然后将Bundle
文件拖进项目中即可,加上.bundle
后缀的文件夹会被Mac
自动识别为一个Bundle
包。

2. 添加资源文件
这个文件在运行的时候不会被编译到,所以此文件中存储的内容必须是资源文件(比如图片、声音),不能是编译的文件(比如能编译运行的代码)。
- 自带的
en.lproj
和Root.plist
用不到的可以删除掉,将需要加入Bundle
的资源文件直接拖进项目中的.bundle
下。

- 或者去根目录下,右键
Bundle
点击显示包内容
,将资源文件直接放进去即可。

3. 使用 Bundle 文件内资源
- 以图片为例,先获取
Bundle
文件路径,然后使用图片路径来引用图片。
NSString *path = [[NSBundle mainBundle] pathForResource:@"xxx" ofType:@"bundle"];
UIImage *image = [UIImage imageWithContentsOfFile:[path stringByAppendingPathComponent:@"xxx.png"]];
- 如果想要获取
Bundle
对象,就使用以下方法:
NSBundle *bundle = [NSBundle bundleWithPath:[[NSBundle mainBundle] pathForResource:@"xxx" ofType:@"bundle"]];
方法就是这样,别的项目中要使用的话直接将
Bundle
文件拖进去即可使用,和普通的文件夹没有什么区别。
将来的你,一定会感激现在拼命的自己,愿自己与读者的开发之路无限美好。