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

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

例:

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

是的,使用位置参数:

// 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");
http://stackoverflow.com/questions/11454103/nsstring-stringwithformat-access-same-parameter-multiple-times

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:objective-c – “NSString stringWithFormat:” – 多次访问相同的参数?