Wednesday, October 12, 2011

Localize Your NSString

I probably won't use this code since I'm pretty sure it's a terrible idea. But since I put it together today, I'll share it. It's an NSString category that overwrite just the stringWithFormat: method, and just replaces the text with the text from your local language bundle.

I thought it would be useful for localizing an application, but it will probably result in madness and, eventually, blindness. It's a category "extension" for NSString.

#import "NSString+Localization.h"

@implementation NSString (Localization)

+ (NSString*)stringWithFormat:(NSString *)text, ...
{
    va_list args;
    va_start(args, text);
    text = NSLocalizedString(text, nil);
    NSString *retVal = [[NSString alloc] initWithFormat:text arguments:args];
    return retVal;
}

Perhaps more sane than overriding the stringWithFormat: method would be to create one. Any help on the name would be appreciated:

#import "NSString+Localization.h"

@implementation NSString (Localization)

+ (NSString*)twiceLocalizedStringWithFormat:(NSString *)text, ...
{
    va_list args;
    va_start(args, text);
    text = NSLocalizedString(text, nil);
    NSString *retVal = [[NSString alloc] initWithFormat:text locale: [[NSUserDefaults standardUserDefaults] dictionaryRepresentation] arguments:args];
    return retVal;
}


NOTE: This code is ARC friendly. If you are not ARCing, autorelease the retVal in both examples.

No comments: