运行时来自NSDictionary的.strings文件

时间:2016-07-02 17:06:47

标签: ios objective-c nsdictionary nsfilemanager nslocalizedstring

我正在请求从服务器检索字符串字典。如何将这些字符串资源写入.strings文件并在运行时检索单个条目?

我知道将文件保存到Library / Application Support目录是可能的,但是我在从文件中检索单个条目时遇到了问题。

// Create directory
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);
NSString *path = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"CFSSLocalizable"];

// Write strings to file - this works
NSString *strings = [myDictionary descriptionInStringsFileFormat];
BOOL fileWasCreated = [strings writeToFile:[NSString stringWithFormat:@"%@/Localizable.strings", path] atomically:NO encoding:NSUTF8StringEncoding error:&anotherError];

现在我无法弄清楚如何从文件中读取条目。

我尝试过创建新的捆绑包:

NSBundle *bundle = [NSBundle bundleWithPath:path];

并从包中读取:

NSString *string = [bundle localizedStringForKey:[key lowercaseString] value:nil table:nil];

但这不是返回值,它只返回键名。我还不相信它甚至会读取正确的文件,因为它返回的关键名称不在我指定的文件中。

有谁知道如何将我的字典内容存储在一个文件中,然后根据该键从该文件中提取单个值?

1 个答案:

答案 0 :(得分:1)

试试这个:

// get the directory path
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);
NSString *targetDirectoryPath = [paths.firstObject stringByAppendingPathComponent:@"CFSSLocalizable"];
if (![fileManager fileExistsAtPath:targetDirectoryPath isDirectory:&isDirectory]) {
    [fileManager createDirectoryAtPath:targetDirectoryPath withIntermediateDirectories:YES attributes:nil error:nil];
}

NSString *targetFilePath = [targetDirectoryPath stringByAppendingPathComponent:@"Localizable.strings"];

// Write strings to file - this works
BOOL fileWasCreated = [strings writeToFile:targetFilePath atomically:NO encoding:NSUTF8StringEncoding error:&anotherError];

// Read file
if (fileWasCreated) {
    NSBundle *bundle = [NSBundle bundleWithPath:targetDirectoryPath];
    NSString *value = NSLocalizedStringFromTableInBundle(@"some key", nil, bundle, nil);
    NSLog(@"value: %@", value);
}