NSBundle的理解和mainBundle的基本介绍

一、NSBundle

NSBundle是cocoa为bundle提供的一个类,bundle是一个目录,其中包含了程序会使用到的资源. 这些资源包含了如图像、声音、编译好的代码、nib文件。(用户也会把bundle称为plug-in)

  bundle中的有些资源可以本地化。例如:对于zw.nib,我们可以有两个版本:一个针对英语用户,一个针对汉语用户。在bundle中就会有两个子目录:English.lproj和Chinese.lproj,我们把各自版本的zw.nib文件放到其中。当程序需要加载zw.nib文件时,bundle会自动根据所设置的语言来加载.(在小码哥最新的MJRefresh中就用到此方法,可以修改刷新时候的提示语言)

  获取bundle的方法,以及简单应用:

 1 - (void)viewDidLoad {
 2     [super viewDidLoad];
 3     //获得bundle
 4     NSBundle *bundle = [NSBundle bundleWithPath:@"/Users/ZW/Desktop/abckd"];
 5     //获取bundle文件中的图片的路径
 6     NSString *path = [bundle pathForResource:@"00" ofType:@"png"];
 7     //获取图片对象
 8     UIImage *image = [[UIImage alloc] initWithContentsOfFile:path];
 9     UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
10     [self.view addSubview:imageView];
11 }

  bundle还有其它用法:bundle中可以包含一个库. 如果我们从库得到一个class, bundle会连接库,并查找该类,等等,以后慢慢研究

二、mainBundle

  我们的程序是一个bundle。 在Finder中,一个应用程序看上去和其他文件没有什么区别。但是实际上它是一个包含了nib文件、编译代码以及其它资源的目录. 我们把这个目录叫做程序的main bundle,获取方式如下

  NSBundle *mainBundle = [NSBundle mainBundle]; 

  应用如下:

 
1 - (void)viewDidLoad {
2     [super viewDidLoad];
3     NSBundle *mainBundle = [NSBundle mainBundle];
4     NSLog(@"%@",mainBundle);
5     NSString *imagePath = [mainBundle pathForResource:@"abc" ofType:@"png"];
6     UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:imagePath]];
7     [self.view addSubview:imageView];
8 }
 

还有其它一些用法,比如加载工具条UIToolbar *toolbar = [[[NSBundle mainBundle] loadNibNamed:@"ZWKeyboardTool" owner:self options:nil] firstObject];等等,后续还有很多实际应用

其它的一些关于NSBundle更详细介绍可以看下博文:http://blog.sina.com.cn/s/blog_8c87ba3b0100t89v.html

原文地址:https://www.cnblogs.com/Free-Thinker/p/9518995.html