29

When I'm using string formatting, can I access one parameter multiple times without passing it again?

Example:

NSString *parameter1 = @"1";
NSString *parameter2 = @"2";

NSString *myString;
myString = [NSString stringWithFormat:@"I want to print parameter1 here: %@, parameter2 here: %@ and now access parameter1 again: %@ _without_ passing it again.",parameter1, parameter2, parameter1];

Is there a way to access the first parameter again without writing ", parameter1" again?

Git.Coach
  • 3,032
  • 2
  • 37
  • 54

2 Answers2

63

Yes, using positional arguments:

// prints: foo bar foo bar
NSLog(@"%@", [NSString stringWithFormat:@"%2$@ %1$@ %2$@ %1$@", @"bar", @"foo"]);

// NSLog supports it too
NSLog(@"%2$@ %1$@ %2$@ %1$@", @"bar", @"foo");
hamstergene
  • 24,039
  • 5
  • 57
  • 72
  • 6
    Note that in the format string, you need to refer to all the arguments supplied in the argument list. eg. The following code will cause a bug at runtime, because the first positional argument is unused in the format string: `[NSString stringWithFormat:@"%2$@", @"bar", @"foo"]` — see http://stackoverflow.com/questions/2946649/nsstring-stringwithformat-swizzled-to-allow-missing-format-numbered-args – mrb Jul 12 '12 at 14:44
  • 1
    @mrb Right. It's side effect of variable arguments (`...`) implementation in C (not a bug). If you don't tell formatting function what type an argument has (by refering to it at least once), there is no way to correctly locate ones after it. – hamstergene Jul 12 '12 at 14:49
  • i try it with predicateWithFormat but not working. how can use argument position for predicate ? – Add080bbA Jul 14 '15 at 16:28
4
NSString *parameter1 = @"1";
NSString *parameter2 = @"2";

NSString *myString;
myString = [NSString stringWithFormat:@"I want to print parameter1 here: %1$@, parameter2 here: %2$@ and now access parameter1 again: %1$@ _without_ passing it again.",parameter1, parameter2];

String Format Specifiers

Max O
  • 997
  • 8
  • 13