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!
Written by Björn Kaiser
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Objective-c
Authors
Related Tags
#objective-c
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#