最近在做一个关于检测版本更新的功能,用到了NSBundle这个类,所以就想总结一下.
一,什么是NSBundle
苹果给出的解释是这样的: An NSBundle object represents a location in the file system that groups code and resources that can be used in a program. NSBundle objects locate program resources, dynamically load and unload executable code, and assist in localization. You build a bundle in Xcode using one of these project types: Application, Framework, plug-ins.
大体的意思是这样的:NSBundle 对象指代相应应用程序下的所有可用的文件系统。就是说,可以用NSBundle操作应用程序下,所有可用的资源(包括,xib文件,数据文件,图片 等)。
网上给出了更加通俗的理解是:因为NSBundle 英语中的解释是:“捆,束”的意思,所以我们可以理解为:NSBundle是将程序中所有资源捆在一起的对象.二,bundle的用法
1) 关于infoDictionary的用法
NSBundle* mainBundle = [NSBundle mainBundle];
NSDictionary* infoDictionary = [mainBundle infoDictionary];
NSLog(@"infoDictionary:%@ ", infoDictionary );
打印结果:
2)获取app的info.plist详细信息
版本号:Bundle versionNSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"];应用标识:Bundle identifier
NSString *bundleId = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleIdentifier"];应用名称:Bundle display name
NSString *appName = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleDisplayName"];Bundle name
NSString *appName = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleName"];3)应用程序语言本地化
#define XLocalizedString(key, comment) [[NSBundle mainBundle] localizedStringForKey:(key) value:@"" table:nil]中英文两个Localizable.strings文件中键值对,例如
"none" = "确定"; "none" = "none";</span>宏的用法:(返回NSString *)
localizedString("none", "这是注释")
4)获取包内文件路径和文件
获取app包路径NSString *path = [[NSBundle mainBundle] bundlePath];app资源目录路径
NSString *resPath = [[NSBundle mainBundle] resourcePath];获取资源目录下a.bundle
NSString* path = [resPath stringByAppendingPathComponent:@"a.bundle"]; NSBundle *bundle = [NSBundle bundleWithPath:path];获取app包的readme.txt文件路径
NSString *path = [[NSBundle mainBundle] pathForResource:@"readme" ofType:@"txt"];获取XML文件
NSString *filePath = [[NSBundle mainBundle] pathForResouse:@"re" ofType:@"xml"]; NSData *data = [[NSData alloc] initWithContentsOfFile:filePath];获取属性列表
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"ViewControllers" ofType:@"plist"]];NSBundle负责(在后台)加载nib文件.
BOOL flag = [NSBundle loadNibNamed:@"ViewController" owner:someObject]; //注意噢, 我们指定了一个对象someObject作为nib的File”s Owner