Open .string files as an NSDictionary

2019-09-06 08:12发布

问题:

How do I open a .string file as an NSDictionary?

Edit: I want to be able to use it like this:


NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:@"dict.plist"];
NSDictionary *strings = [[NSDictionary alloc] initWithContentsOfFile:@"Strings.strings"];


回答1:

If you really want it in a dictionary, you can load it using [NSDictionary dictionaryWithContentsOfFile:], since it is in “Old-style ASCII” format. I have used this technique before on Mac OS X, but I'm not sure you can do the same for iOS.

However, if you want a translation for a particular string, there are at least two ways to do it:

  1. NSLocalizedStringFromTable() will allow you to load strings from files other than the normal Localizable.strings file. Provide the name of your strings file (without the extension).

  2. NSBundle's localizedStringForKey:value:table: method. This essentially performs the same operations as the method above, and as above, provide the name of your strings file without the extension.



回答2:

.string files just store key/value pairs, like:

"StringKey" = "some localized text";

you can get the text for a specific key using NSLocalizedString. If you want to get all the strings in a file, I suppose you could read the Localizable.strings file and parse it.