bundle是一个目录,其中包含了程序会使用到的资源,这些资源包含了如图像、编译好的代码、nib文件等。对应bundle,cocoa提供了类NSBundle。这个类的对象,就是定位了程序使用的资源在文件系统里的位置,并可以动态的加载、或者卸载掉可执行代码。
我们的程序是一个bundle,在Finder中,一个应用程序看上去和其他文件没有什么区别,但是实际上它是一个包含了nib文件,编译代码,以及其他资源的目录。我们把这个目录叫做程序的main bundle,在 xcode 里,使用应用程序、框架、或者插件的时候,xcode 会生成对应的资源的目录包。
NSBundle *mainBundle = [NSBundle mainBundle];
[NSBundle mainBundle]是获得NSBundle的一个单例对象,此单例对象已经设置了默认的resourcePath,也就是你的app打包后的路径。
NSString *resourcePath = [[NSBundle mainBundle] resourcePath];
查找自定义的bundle。
// 1. 在main bundle中找到特定bundle路径
NSString*customerBundlePath = [[NSBundle mainBundle] pathForResource:@"Customer" ofType:@"bundle"];
// 2. 载入bundle
NSBundle*customerBundle = [NSBundle bundleWithPath:customerBundlePath];
通过bundle加载xib文件。
UIView *customerView = [[NSBundle mainBundle] loadNibNamed:@"customerView" owner:self options:nil];
小知识:imageWithContentsOfFile
官方文档说 imageWithContentsOfFile是可以自动区分@2x @3x的图片的,于是就在工程里拖入pic@2x和pic@3x两张图片,然后使用如下代码:
NSString *path = [[NSBundle mainBundle] pathForResource:@"pic" ofType:@"png"];
imageView.image = [UIImage imageWithContentsOfFile:path];
但是并没有获取到图片,返回的path打印的结果为空。是不是获取的path有问题,然后:
NSString *path = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"pic.png"];
imageView.image = [UIImage imageWithContentsOfFile:path];
果然获取到了图片。
应该是第一种获取到的是具体的某一个文件,如pic就是pic,所以用pic来获取图片的地址,根本就不存在pic这个图片。而第二种获取到的是类似文件的相对路径,具体这里面的@2x、@3x就是imageWithContentsOfFile自动来匹配了。
网友评论