Once you’ve mastered using localized strings in Xcode 4, you can move on to performing substitutions in those strings.
The benefit of this approach is two-fold. Strings values easily calculated at runtime don’t need to be individually defined, and those same strings can still be localized.
For example, let’s say you have a UITableView, and for each cell you want to display its index in the table:
Instead of five individually defined strings, you’d have a single string in your Localizable.strings file with a placeholder for the table index:
|
/* Localizable.strings How to Perform String Substitutions in Xcode 4 Created by Miscellanea on 11/24/11. "CellTitle" = "Item #%s"; |
Then in your UITableViewController implementation you’d reference the string and perform a substitution for the table index:
|
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView if (cell == nil) // FIXME: we'll improve this in a later post! case (1): case (2): case (3): case (4): default: [cell.textLabel setText:[NSLocalizedString(@"CellTitle", @"") |
This isn’t limited to numeric substitutions; it’s especially useful for titles and labels with prefixes, or anywhere a string needs to reflect a dynamic state or view.
In a future post I’ll explain a much better way to display numbers as strings.


Leave a comment
Comments feed for this article