Monday, April 29, 2013

NSBundle localizedStringForKey example ios

localizedStringForKey :value:table:

Returns a localized version of the string designated by the specified key and residing in the specified table.
- (NSString *)localizedStringForKey:(NSString *)key value:(NSString *)valuetable:(NSString *)tableName
The key for a string in the table identified by tableName.
The value to return if key is nil or if a localized string for key can’t be found in the table.
The receiver’s string table to search. If tableName is nil or is an empty string, the method attempts to use the table in Localizable.strings.
Return Value of [NSBundle localizedStringForKey]
A localized version of the string designated by key in table tableName. If value is nil or an empty string, and a localized string is not found in the table, returns key. If key and value are both nil, returns the empty string.
Discussion of [NSBundle localizedStringForKey]
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 localizedStringForKey :value:table: to log a message when the method can’t find a localized string. If you set this default to YES (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.[NSBundle localizedStringForKey]
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:
Example of [NSBundle localizedStringForKey]
- (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;