bundle是一个目录,其中包含了程序会使用到的资源. 这些资源包含了如图像,声音,文本文件,属性列表,语言包,编译好的代码,nib文件(用户也会把bundle称为plug-in). 对应bundle,cocoa提供了类NSBundle.我们的程序是一个bundle. 在Finder中,一个应用程序看上去和其他文件没有什么区别. 但是实际上它是一个包含了nib文件,编译代码,以及其他资源的目录. 我们把这个目录叫做程序的main bundle。
1、通过使用下面的方法得到程序的main bundle
NSBundle *myBundle = [NSBundle mainBundle];
2、使用NSBundle加载nib文件
BOOL successful = [NSBundle loadNibNamed:@"About" owner:someObject];
self.titleView = [[[NSBundle mainBundle]loadNibNamed:NSStringFromClass([CCNearbyTitleView class]) owner:self options:nil] firstObject];
3、使用NSBundle加载xml文件
NSString *filePath = [[NSBundle mainBundle] pathForResouse:@"re" ofType:@"xml"];
NSData *data = [[NSData alloc] initWithContentsOfFile:filePath];
4、使用NSBundle加载图片文件
NSString *filePath = [[NSBundle mainBundle] pathForResouse:@"AppIcon" ofType:@"png"];
UIImage *image=[UIImage imageWithContentsOfFile:filePath];
//同理这个[UIImage imageNamed:@"AppIcon"];
5、 使用NSBundle加载本地语言包
中文
"change_language" = "悄悄是别离的笙箫,沉默是今晚的康桥";
"button" = "切换语言";
英文:
"change_language" = "Quietness is my farewell music, silence is Cambridge tonight";
"button" = "Change Language";
NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
NSString *currLanguage = [def valueForKey:@"LocalLanguageKey"];
if(!currLanguage){
NSArray *preferredLanguages = [NSLocale preferredLanguages];
currLanguage = preferredLanguages[0];
if ([currLanguage hasPrefix:@"en"]) {
currLanguage = @"en";
}else if ([currLanguage hasPrefix:@"zh"]) {
currLanguage = @"zh-Hant";
}else currLanguage = @"en";
[def setValue:currLanguage forKey:@"LocalLanguageKey"];
[def synchronize];
}
NSString *path = [[NSBundle mainBundle] pathForResource:[[NSUserDefaults standardUserDefaults] objectForKey:@"LocalLanguageKey"] ofType:@"lproj"];
NSBundle* bundle = [NSBundle bundleWithPath:path];
//此处是上面赋值的bundle
NSString *str = [bundle localizedStringForKey:@"change_language" value:nil table:@"MultiLanguage"];
NSString *buttonStr = [bundle localizedStringForKey:@"button" value:nil table:@"MultiLanguage"];
NSLog(@"wenzi:%@,%@",str,buttonStr);