Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does this %1$@%2$d format specifier means in objective c

I've been working with format specifiers but they were generic like %d or %@ but today in a tutorial I saw these %1$@%2$d and didn't understand what they represent.
It was a calculator example so they are using them in this statement: stack = [NSString stringWithFormat:@"%1$@%2$d",stack,number];

like image 288
Chaudhry Talha Avatar asked Nov 04 '15 09:11

Chaudhry Talha


1 Answers

The numbers represent positional parameters. The parameters which follow the format string are slotted into the string based on their position in the parameters list. The first parameter goes into the %1 slot, the second into the %2 slot, and so on. The purpose is to deal with languages where the order of terms/words/etc might change from your default. You can't change the parameter order at runtime, but you can make sure the parameters end up in the correct place in the string.

Example

NSLog(@"%1$@, %2$@", @"Red", @"Blue");
NSLog(@"%2$@, %1$@", @"Red", @"Blue");

Output

Red, Blue
Blue, Red

Note that the format string changed, but the parameters are in the same order.

like image 69
Avi Avatar answered Nov 09 '22 23:11

Avi