Bundle文件可以理解为一个资源包,用于存储图片、音频、文本、nib文件等,方便在其他项目中引用包内的资源。bundle包是静态的,不参与编译,也就意味着,bundle 包中不能包含可执行的文件。它仅仅是作为资源,被解析成为特定的 2 进制数据。
一、创建方式
1、简单创建:创建一个文件, 将该文件重命名成后缀为.bundle的文件
2、通过X-Code创建
新建一个工程:
![](https://img.haomeiwen.com/i6319734/70acef6c1dc965c4.png)
![](https://img.haomeiwen.com/i6319734/e6055d41506f6a27.png)
![](https://img.haomeiwen.com/i6319734/abf225b2b9b43b52.png)
![](https://img.haomeiwen.com/i6319734/c1b13bb78eeb34d9.png)
添加资源到工程:
![](https://img.haomeiwen.com/i6319734/f09ea03faa7d3936.png)
此时可以看到.bundle文件是红色的,接下来分别选一个模拟器和Generic iOS Device编译一下,分别代表真机和模拟器
![](https://img.haomeiwen.com/i6319734/619f1db58436dcdf.png)
运行过后.bundle文件变成了黑色,选中该文件show in Finder
![](https://img.haomeiwen.com/i6319734/13b43c8f145abb26.png)
里面有相对应的真机和模拟器的生成的.bundle文件
![](https://img.haomeiwen.com/i6319734/f83bf03925e1f5a8.png)
Bundle文件的使用:
直接在这个工程中,创建一个App项目。然后把这个Bundle资源包添加(直接拖也OK)进去调用即可
![](https://img.haomeiwen.com/i6319734/b2b405303b305bba.png)
![](https://img.haomeiwen.com/i6319734/d0cbf0dfc6f7943c.png)
![](https://img.haomeiwen.com/i6319734/91f9ea24114631b4.png)
//如果不像上面这样,直接新建一个工程将bundle包直接拖到新工程中使用也是OK的
具体访问文件方法:(以图片为例)
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, 100, 100)];
//获取bundle路径的两种方式
NSString *path = [[NSBundle mainBundle] pathForResource:@"MyDemo" ofType:@"bundle"];
// NSString *path = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"MyDemo"];
NSBundle *bundle = [NSBundle bundleWithPath:path];
//获取image的两种方式
imageView.image = [UIImage imageNamed:@"emojy" inBundle:bundle compatibleWithTraitCollection:nil];
// imageView.image = [UIImage imageNamed:@"MyDemo.bundle/emojy"];
[self.view addSubview:imageView];
如果有nib文件:
NSString *path = [[NSBundle mainBundle] pathForResource:@"MyDemo" ofType:@"bundle"];
// NSString *path = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"MyDemo"];
NSBundle *bundle = [NSBundle bundleWithPath:path];
UINib *nib = [UINib nibWithNibName:NSStringFromClass([@"YourClassName" class]) bundle:bundle];
网友评论