“NSString stringWithFormat:” - 多次访问相同的参数?

时间:2012-07-12 14:30:14

标签: objective-c nsstring string-formatting

当我使用字符串格式时,我可以多次访问一个参数而不再传递它吗?

示例:

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];

有没有办法再次访问第一个参数而不再写“,parameter1”?

2 个答案:

答案 0 :(得分:59)

是的,使用位置参数

// 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");

答案 1 :(得分: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