Last Updated: February 25, 2016
·
1.566K
· codegefluester

NSLocalizedString with placeholders

When you're using the built in functions to localize your iOS/Mac App you may some day having strings like "Hello %@!" etc.. This little handy Objective-C method will assist you in formatting your localized strings

+ (NSString*) localizedFormat:(NSString*)translationKey parameters:(NSArray*)params
{
    NSRange range = NSMakeRange(0, [params count]);
    NSMutableData* data = [NSMutableData dataWithLength: sizeof(id) * [params count]];

    [params getObjects: (__unsafe_unretained id *)data.mutableBytes range:range];

    return [[NSString alloc] initWithFormat: NSLocalizedString(translationKey, @"") arguments: data.mutableBytes];
}

Simply call it like this (I wrapped it in a helper class but you could also add it as a NSString category):

[myLabel setText:[MyHelperClass localizedFormat:@"MY_KEY" parameters:[NSArray arrayWithObjects:@"Peter"]]];

This would output Hello Peter!