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

在Objective-C中读取.strings文件?,objective-c,Objective C,我正在创建一个Mac应用程序,我想本地化我的标签。我认为.strings文件是更好的选择。但是我在Objective-C中读取.strings文件时遇到困难。我正在寻找一种更简单的方法 这是我的.string文件内容: "LABEL_001" = "Start MyApp"; "LABEL_002" = "Stop MyApp"; "LABEL_003" = "My AppFolder"; ... 我已经看过了 这是我的代码: NSBundle *bundle = [NSBundle main

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

这是我的
.string
文件内容:

"LABEL_001" = "Start MyApp";
"LABEL_002" = "Stop MyApp";
"LABEL_003" = "My AppFolder";
...
我已经看过了

这是我的代码:

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”


我做错了什么?一个。您必须将文件命名为app bundle中
.lproj
目录下的
Localizable.strings

两个。使用
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"];
我想这会对您有所帮助。

这是您的代码

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扩展名的文件名


希望这有帮助。

简单代码

只需创建一个方法,如下所示

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

你看过NSLocalizedString吗?Swift4,同样的想法,仍然有用。谢谢
- (void)localisationStrings
{
    NSString* path = [[NSBundle mainBundle] pathForResource:@"localisation" ofType:@"strings"];
    NSDictionary *localisationDict = [NSDictionary dictionaryWithContentsOfFile:path];
    NSLog(@"\n %@",[localisationDict objectForKey:@"hello"]);
}