2012-08-17 80 views
6

我正在創建一個Mac應用程序,我想本地化我的標籤。我認爲.strings文件將是一個更好的選擇。但是我在閱讀Objective-C中的.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"

我在做什麼錯?

+0

你看着NSLocalizedString? – Luke 2012-08-17 10:44:11

回答

23

一。您必須在應用包中的<LANGUAGENAME>.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"]; 
+0

其工作很好 – svmrajesh 2015-09-15 10:01:03

2
NSString *path = [[NSBundle mainBundle] pathForResource:@"Labels" ofType:@"strings"]; 
    NSData *plistData = [NSData dataWithContentsOfFile:path]; 
    NSString *error; NSPropertyListFormat format; 

    NSDictionary *dictionary = [NSPropertyListSerialization propertyListFromData:plistData 
                  mutabilityOption:NSPropertyListImmutable 
                    format:&format 
                  errorDescription:&error]; 
    NSString *stringname = [dictionary objectForKey:@"LABEL_001"]; 

我認爲這將是對你有所幫助。

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」,將其更改爲@「標籤」,所以上面的代碼會變得,

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

僅供參考,從Apple文檔複製了關於表名稱的以下行, 「爲此參數指定值時,請包含不帶.strings擴展名的文件名。」

希望這有助於。

0

簡單代碼

只需創建一個方法如下

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