在Objective-C中读取.strings文件?

时间:2012-08-17 10:39:03

标签: objective-c

我正在创建一个Mac应用,我想要本地化我的标签。我认为.strings文件是更好的选择。但是我在Objective-C中阅读.strings文件时遇到了麻烦。我正在寻找一种更简单的方法。

这是我的.string文件内容:

"LABEL_001" = "Start MyApp";
"LABEL_002" = "Stop MyApp";
"LABEL_003" = "My AppFolder";
...

我已经查看了http://developer.apple.com/library/mac/#documentation/cocoa/conceptual/LoadingResources/Strings/Strings.html

这是我的代码:

NSBundle *bundle = [NSBundle mainBundle];
NSString *strFilePath = [[NSBundle mainBundle] pathForResource:@"Labels" ofType:@"strings"];
NSString *tt =NSLocalizedStringFromTableInBundle(@"LABEL_001",strFilePath,bundle, nil);
NSLog(@"STRING ::: %@",tt);

但是字符串tt给出"LABEL_001",我想要"Start MyApp"

我做错了什么?

3 个答案:

答案 0 :(得分:25)

一。您必须在应用程序包的Localizable.strings目录中命名文件<LANGUAGENAME>.lproj

两个。使用NSLocalizedString宏:

NSString *loc = NSLocalizedString(@"LABEL_001", nil);

三。如果没有任何效果,您可以使用字符串文件初始化NSDictionary,因为字符串文件是一种特殊类型的plist:

NSString *fname = [[NSBundle mainBundle] pathForResource:@"whatever" ofType:@"strings"];
NSDictionary *d = [NSDictionary dictionaryWithContentsOfFile:fname];
NSString *loc = [d objectForKey:@"LABEL_001"];

答案 1 :(得分:1)

这是你的代码

NSBundle *bundle = [NSBundle mainBundle];
NSString *strFilePath = [[NSBundle mainBundle] pathForResource:@"Labels" ofType:@"strings"];
NSString *tt =NSLocalizedStringFromTableInBundle(@"LABEL_001",strFilePath,bundle, nil);
NSLog(@"STRING ::: %@",tt);

这里的问题是第二个参数“strFilePath”,将其更改为@“Labels”,以便上面的代码变为,

NSString *tt =NSLocalizedStringFromTableInBundle(@"LABEL_001",@"Labels",bundle, nil);

作为参考,从Apple Docs复制以下关于表名的行, “为此参数指定值时,请包含不带.strings扩展名的文件名。”

希望这会有所帮助。

答案 2 :(得分:0)

简单代码

只需创建如下方法

- (void)localisationStrings
{
    NSString* path = [[NSBundle mainBundle] pathForResource:@"localisation" ofType:@"strings"];
    NSDictionary *localisationDict = [NSDictionary dictionaryWithContentsOfFile:path];
    NSLog(@"\n %@",[localisationDict objectForKey:@"hello"]);
}