2010-06-30 37 views
13

我想從localizable.strings文件中讀取文本。我正在從一個.strings文件中收集幾個目錄和文件的翻譯字符串。但是,我有幾個相同的翻譯字符串的副本。我想以編程方式刪除此。 所以我需要從.strings文件中只讀取字符串(不是註釋),然後 - 然後對它們進行排序, - 刪除重複的字符串 然後創建一個新的.strings文件。iphone - 從Localizable.strings文件讀取作爲字典中的鍵值

是否可以讀取字符串文件並將字符串和翻譯的值保存在字典中。我的意思是任何內置方法來讀取.text文件,只有「key」=「value」部分,避免/ * ... * /或#comments部分。就像讀一個配置文件一樣。

+0

MXG - 你大概是這個意思的答案。 – Jonny 2014-07-08 02:21:16

回答

7

我很高興在NSString類中找到一個很好的API。代碼如下。

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification { 
// Insert code here to initialize your application 
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Localizable" ofType:@"strings"]; 
NSString *fileText = [NSString stringWithContentsOfFile:filePath encoding: NSUnicodeStringEncoding error:nil]; 
NSDictionary *stringDictionary = [fileText propertyListFromStringsFileFormat]; 

NSArray *allKeys = [stringDictionary allKeys]; 

NSArray *sortedKeys = [allKeys sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)]; 

NSString *documentsDirectory; 
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES); 
if ([paths count] > 0) {  
    documentsDirectory = [paths objectAtIndex:0];  
} 

NSString *outputPath = [documentsDirectory stringByAppendingString:@"/Localizable.strings"]; 
NSLog(@"Strings contents are writing to: %@",outputPath); 
[[NSFileManager defaultManager] createFileAtPath:outputPath contents:nil attributes:nil]; 
NSFileHandle *outputHandle = [NSFileHandle fileHandleForWritingAtPath:outputPath]; 
[outputHandle seekToEndOfFile]; 

for(id key in sortedKeys){ 
    NSString *line = [NSString stringWithFormat:@"\"%@\" = \"%@\";\n", key, [stringDictionary objectForKey:key]]; 
    NSLog(@"%@",line); 
    [outputHandle writeData:[line dataUsingEncoding:NSUnicodeStringEncoding]]; 
} 
} 
+4

我發現.strings文件被編譯成一個「二進制屬性列表」。這可以加載:[NSDictionary dictionaryWithContentsOfFile:path]; – 2010-08-18 16:52:50

52
NSString *path = [[NSBundle mainBundle] pathForResource:@"Localizable" 
                ofType:@"strings"              
               inDirectory:nil 
              forLocalization:@"ja"]; 

    // compiled .strings file becomes a "binary property list" 
    NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:path]; 

    NSString *jaTranslation = [dict objectForKey:@"hello"]; 
+0

簡直太棒了! – mxg 2011-11-26 07:11:35

+1

實際上,它也適用於常規(utf-8和utf-16).strings文件。 – 2013-02-19 14:07:11

0

我一直在尋找的就是讀取從包文件中的JSON爲NSDictionary,然後打印一個UITextView內的一種方式。 結果沒有很好地格式化!

我用卡里姆的答案的一部分,從上面創建生成的字符串中的某個美化JSON的方法:

-(void)setText:(NSDictionary *)json 
{ 
    NSArray *allKeys = [json allKeys]; 

    _beautyStr = @""; 
    for(id key in allKeys){ 
     NSString *line = [NSString stringWithFormat:@"\"%@\" = \"%@\";\n", key, [text objectForKey:key]]; 
    _beautyStr = [NSString stringWithFormat:@"%@%@",_beautyStr, line]; 
    } 

    NSLog(@"%@",_beautyStr); 
} 
相關問題