How do I localize a string that has placeholders in it with NSLocalizedString?
For example:
[NSString stringWithFormat:@"You can afford %i at %@%li.",[kCash integerValue]/self.price, kYen, self.price]
How do I localize this? Do I do break up the strings into multiple localized strings? How then do I deal with varying sentence structure and grammar?
An unique identifier is attached to each translated string called the "Localization Identifier". It is used to search the dictionaries and locate the value of the string in different languages.
Select the project and under “Localizations”, click the “+” icon. Add any language you want (I selected Italian) then click on “Finish”. Now go back to Localizable. string file, select it and on the File Inspector (right menu) select “Localize”.
NSLocalizedString won't alter your placeholders, so stringWithFormat can use them as normal. In your example, using numbered placeholders is probably a good idea -
[NSString stringWithFormat:@"You can afford %1$i at %2$@%3$li.", [kCash integerValue]/self.price, kYen, self.price]
More info here: Is there a way to specify argument position/index in NSString stringWithFormat?
Have the localized strings include the placeholders. That's pretty much the only proper way to do it as otherwise, as you mentioned, you couldn't take varying word order into account.
Something along these lines:
[NSString stringWithFormat:NSLocalizedString(@"Foo %i", @"Foo %i"), 123]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With