views:

165

answers:

2

I have tried using a variable as an input parameter to NSLocalizedString, but all I am getting back is the input parameter. What am I doing wrong? Is it possible to use a variable string value as an index for NSLocalized string?

For example, I have some strings that I want localized versions to be displayed. However, I would like to use a variable as a parameter to NSLocalizedString, instead of a constant string. Likewise, I would like to include formatting elements in the parameter for NSLocalizedString, so I would be able to retrieved a localized version of the string with the same formatting parameters. Can I do the following:

Case 1: Variable NSLocalizedstring:

NSString *varStr = @"Index1";
NSString *string1 = NSLocalizedString(varStr,@"");

Case 2: Formatted NSLocalizedString:

NSString *string1 = [NSString stringWithFormat:NSLocalizedString(@"This is an %@",@""),@"Apple"];

(Please note that the variable can contain anything, not just a fixed set of strings.)

Thanks!

+1  A: 

If what you want is to return the localized version of "This is an Apple/Orange/whatever", you'd want:

NSString *localizedVersion = NSLocalizedString(([NSString stringWithFormat:@"This is an %@", @"Apple"]), nil);

(I.e., the nesting of NSLocalizedString() and [NSString stringWithFormat:] are reversed.)

If what you want is the format to be localized, but not the substituted-in value, do this:

NSString *finalString = [NSString stringWithFormat:NSLocalizedString(@"SomeFormat", nil), @"Apple"];

And in your Localizable.strings:

SomeFormat = "This is an %@";
Wevah
Yeah, but the variable can contain anything, not just "apples" or "oranges". So I need to maintain flexibility.
futureelite7
Let me append my answer just in case.
Wevah
A: 

Your ideas should work. But if you are getting back the input parameter, that means that the input parameter was not found as a key in your Localizable.strings file. Check the syntax and location of that file.

JWWalker