什么是bundle
bundle是一个包含了某个程序会使用资源的目录,这些资源比如图像,编译好的代码,nib文件(UI文件)
有两种表现形式
一种是保存可执行代码 app就是一个bundle 因为每个App内部的结构都是固定的,而且App这个Bundle就是在编程中经常使用的main bundle。
另一种就是一些资源 比如图像,nib文件(UI文件)
添加到工程里面的资源会在编译的时候复制到main bundle 只有在copy bundle Resouce中的资源才会被复制过去 直接向工程中添加的资源和通过Asset Catalog方式添加的资源都会在Copy Bundle Resource中可能没有显示,这是需要点击Copy Bundle Resouce下面的"+"按钮手动添加,否则main Bundle中就不会有该资源文件,在代码中使用该资源文件时可能会出现问题
获取Bundle
获取mainBundle
NSBundle *myBundle = [NSBundle mainBundle];
获取其他Bundle
NSBundle *goodBundle;
goodBundle = [NSBundle bundleWithPath:@"~/.myApp/Good.bundle"];
获取Bundle中的资源
NSString *path = [goodBundle pathForImageResource:@"Mom"];
Bundle可以包含一个库 库里面可以包含class
bundle会连接库,并查找该类
Class newClass = [goodBundle classNamed:@"Rover"];
id newInstance = [[newClass alloc] init];
Bundle可以加载nib文件
loadNibNamed
//一
NSBundle *bundle = [NSBundle bundleForClass:[self class]];
if (![bundle loadNibNamed:self.className owner:self topLevelObjects:nil]) {
return;
}
//二
HYLShopView *shopView=[[[NSBundle mainBundle]loadNibNamed:NSStringFromClass([self class]) owner:nil options:nil] firstObject];
initWithNibName
self = [super initWithNibName:NSStringFromClass([self class]) bundle:[NSBundle bundleForClass:[self class]]];