CSLocalizedString from strings files?

Any tips on how to get a dictionary to pass to -[CSLocalizedString initWithLocalizedStrings:] from strings files? There doesn't seem to be a straightfoward way to get a string localized in the non-current language.

You can do this (see below) but it’s not exactly fun. If you need this sort of thing a lot, I encourage you to file an enhancement request for it. And if you do that, please post your bug number, just for the record.

To work around this you can exploit the fact that

.strings
files are one of the supported dictionary serialisation formats, that is, you can initialise a dictionary from a
.strings
file. So you can write code like this:
- (NSDictionary *)localizedStringDictionaryForKey:(NSString *)key table:(NSString *)tableName bundle:(NSBundle *)bundle {
    NSMutableDictionary *  result;

    result = [[NSMutableDictionary alloc] init];
    for (NSString * readLoc in [bundle localizations]) {
        NSString *      writeLoc;
        NSURL *        tableURL;
        NSDictionary *  tableDict;
        NSString *      localizedString;

        writeLoc = readLoc;
        if ([readLoc isEqual:@"Base"]) {
            writeLoc = bundle.developmentLocalization;
        }
        tableURL = [bundle URLForResource:tableName withExtension:@"strings" subdirectory:nil localization:readLoc];
        if (tableURL != nil) {
            tableDict = [[NSDictionary alloc] initWithContentsOfURL:tableURL];
            if (tableDict != nil) {
                localizedString = tableDict[key];
                if (tableDict[key] != nil) {
                    result[writeLoc] = localizedString;
                }
            }
        }
    }
    return result;
}

IMPORTANT This is crazy inefficient. If you’re doing this for lots of strings, you’ll want to process the dictionaries in bulk and cache the results.

Share and Enjoy

Quinn "The Eskimo!"
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"
CSLocalizedString from strings files?
 
 
Q