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?

0

2 Answers 2

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");
3
  • 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 stackoverflow.com/questions/2946649/…
    – mrb
    Commented Jul 12, 2012 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. Commented Jul 12, 2012 at 14:49
  • i try it with predicateWithFormat but not working. how can use argument position for predicate ?
    – Add080bbA
    Commented Jul 14, 2015 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

Not the answer you're looking for? Browse other questions tagged or ask your own question.