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");
Sign up to request clarification or add additional context in comments.

3 Comments

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 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.
i try it with predicateWithFormat but not working. how can use argument position for predicate ?
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.