profile for monkeydom at Stack Overflow, Q&A for professional and enthusiast programmers


coding bits I use, come across, like, hate, the whole shebang.

twitter | github | mastodon     rant-dom     rss | archive


NSString stringWithFormat: - indexed arguments!

A IMHO quite underused feature of the format string is indexed parameter referencing. Something that can’t be found easily in the documentation sadly, but is quite crucial for good localization and can be also be used if you want to use an argument more than once:

NSString *formatString = @"Page %1$d of %2$d";
[NSString stringWithFormat:formatString,5,120];
// results in @"Page 5 of 120" 

If you use the indexed argument list, then you can easily change the order the arguments are used:

NSString *formatString = @"Total Pages:%2$d - Current Page:%1$d";
[NSString stringWithFormat:formatString,5,120];
// results in @"Total Pages:120 - Current Page:5" 

Or even use one value twice, or not at all:

NSString *formatString = @"(Total Pages:%2$d) %1$d/%2$d";
[NSString stringWithFormat:formatString,5,120];
// results in @"(Total Pages:120) 5/120"

This works with all types of placeholders, just inject n$ between the % and the actual type of the identifier. 1$ is the first argument, 2$ the second and so on.