NSBundle简要介绍

一、NSBundle

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

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

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

 - (void)viewDidLoad {
     [super viewDidLoad];
     //获得bundle
     NSBundle *bundle = [NSBundle bundleWithPath:@"/Users/ZW/Desktop/abckd"];
     //获取bundle文件中的图片的路径
     NSString *path = [bundle pathForResource:@"00" ofType:@"png"];
     //获取图片对象
     UIImage *image = [[UIImage alloc] initWithContentsOfFile:path];
     UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
     [self.view addSubview:imageView];
 }
bundle还有其它用法:bundle中可以包含一个库. 如果我们从库得到一个class, bundle会连接库,并查找该类,等等。

二、mainBundle

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

NSBundle *mainBundle = [NSBundle mainBundle];
举例:
- (void)viewDidLoad {
[super viewDidLoad];

NSBundle *mainBundle = [NSBundle mainBundle];

NSLog(@"%@",mainBundle);

NSString *imagePath = [mainBundle pathForResource:@"abc" ofType:@"png"];

UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:imagePath]];

[self.view addSubview:imageView];

}

其它一些用法,例如加载工具条UIToolbar *toolbar = [[[NSBundle mainBundle] loadNibNamed:@"ZWKeyboardTool" owner:self options:nil] firstObject];等等。

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
除了使用NSBundle的pathForResource:ofType:方法之外,还有其他几种方法可以在Objective-C中通过类名获取文件名。 1. 使用NSString的方法stringByAppendingString:将类名与文件类型拼接起来,然后使用NSFileManager的方法fileExistsAtPath:判断文件是否存在。 ``` NSString *className = NSStringFromClass([MyClass class]); NSString *filePath = [[NSBundle mainBundle] resourcePath]; NSString *fileName = [className stringByAppendingString:@".m"]; NSString *fullPath = [filePath stringByAppendingPathComponent:fileName]; if ([[NSFileManager defaultManager] fileExistsAtPath:fullPath]) { // 文件存在 } ``` 在这个示例中,我们首先获取类名,然后使用NSBundle的resourcePath方法获取资源路径,然后将类名与文件类型拼接起来,得到完整的文件名。最后,使用NSFileManager的fileExistsAtPath方法判断文件是否存在。 2. 使用C函数objc_getClass和class_getName获取类名,然后使用C函数dlopen和dlsym获取文件名。 ``` #include <dlfcn.h> #import <objc/runtime.h> Class class = objc_getClass("MyClass"); const char *className = class_getName(class); void *handle = dlopen(NULL, RTLD_NOW); const char *fileName = dlsym(handle, className); ``` 在这个示例中,我们首先使用objc_getClass和class_getName函数获取类名,然后使用dlopen和dlsym函数获取文件名。需要注意的是,dlopen和dlsym函数需要传入正确的动态链接库文件路径,否则会出现错误。 总的来说,虽然可以使用多种方法在Objective-C中通过类名获取文件名,但是使用NSBundle的pathForResource:ofType:方法是最常用的方法,也是最简单的方法。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值