localizedString(forKey:value:table:)
Returns a localized version of the string designated by the specified key and residing in the specified table.
Declaration
func localizedString(forKey key: String, value: String?, table tableName: String?) -> StringParameters
- key:
The key for a string in the table identified by
tableName. - value:
The value to return if
keyisnilor if a localized string forkeycan’t be found in the table. - tableName:
The receiver’s string table to search. If
tableNameisnilor is an empty string, the method attempts to use the table inLocalizable.strings.
Return Value
A localized version of the string designated by key in table tableName. This method returns the following when key is nil or not found in table:
If
keyisnilandvalueisnil, returns an empty string.If
keyisnilandvalueis non-nil, returns value.If
keyis not found andvalueisnilor an empty string, returnskey.If
keyis not found andvalueis non-niland not empty, returnvalue.
Discussion
For more details about string localization and the specification of a .strings file, see “String Resources.”
Using the user default NSShowNonLocalizedStrings, you can alter the behavior of localizedString(forKey:value:table:) to log a message when the method can’t find a localized string. If you set this default to true (in the global domain or in the application’s domain), then when the method can’t find a localized string in the table, it logs a message to the console and capitalizes key before returning it.
The following example cycles through a static array of keys when a button is clicked, gets the value for each key from a strings table named Buttons.strings, and sets the button title with the returned value:
- (void)changeTitle:(id)sender
{
static int keyIndex = 0;
NSBundle *thisBundle = [NSBundle bundleForClass:[self class]];
NSString *locString = [thisBundle
localizedStringForKey:assortedKeys[keyIndex++]
value:@"No translation" table:@"Buttons"];
[sender setTitle:locString];
if (keyIndex == MAXSTRINGS) keyIndex=0;
}