我想从localizable.strings文件中读取文本。我正在从几个目录中收集用于翻译的字符串,并将文件放在一个.strings文件中。但后来我有几个相同翻译字符串的副本。我想以编程方式删除它。 所以我需要从.strings文件中读取字符串(而不是注释),以及 - 然后对它们进行排序 - 删除重复的字符串 然后创建一个新的.strings文件。
是否可以读取字符串文件并将字符串和翻译后的值保存在字典中。我的意思是任何读取.text文件的内置方法,只有“key”=“value”部分,避免使用/ * ... * /或#views部分。就像阅读配置文件一样。
答案 0 :(得分:60)
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"];
答案 1 :(得分:8)
我很高兴在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]];
}
}
答案 2 :(得分:1)
Swift解决方案
我按照@ jason-moore above回答的Objective-C代码创建了一个快速代码 该解决方案是等效的。
guard let path = Bundle.main.url(forResource: "Localizable", withExtension: "strings", subdirectory: nil, localization: "ja") else {
return nil
}
guard let dict = NSDictionary(contentsOf: path) else {
return nil
}
guard let jaTranslation = dict.value(forKey: "hello") as? String else {
return nil
}
答案 3 :(得分:0)
我想要的是一种从包文件中读取json到NSDictionary
然后在UITextView
内打印的方法。
结果没有很好的格式化!
我使用了Karim上面的答案的一部分创建了一个在字符串中生成美化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);
}