29

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

例子:

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”?

4

2 回答 2

63

是的,使用位置参数

// 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");
于 2012-07-12T14:39:32.363 回答
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];

字符串格式说明符

于 2012-07-12T14:41:38.033 回答