Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"NSString stringWithFormat:" - Access same parameter multiple times?

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?

like image 785
Git.Coach Avatar asked Jul 12 '12 14:07

Git.Coach


2 Answers

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"); 
like image 174
hamstergene Avatar answered Sep 30 '22 21:09

hamstergene


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

like image 20
Max O Avatar answered Sep 30 '22 20:09

Max O