2012-07-12 60 views
23

當我使用字符串格式時,我可以多次訪問一個參數而不再傳遞一次嗎?「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]; 

有沒有不用寫再次訪問的第一個參數的方式」,參數1" 再次?

回答

54

是,使用定位參數

// prints: foo bar foo bar 
NSLog(@"%@", [NSString stringWithFormat:@"%[email protected] %[email protected] %[email protected] %[email protected]", @"bar", @"foo"]); 

// NSLog supports it too 
NSLog(@"%[email protected] %[email protected] %[email protected] %[email protected]", @"bar", @"foo"); 
+5

注意格式字符串,你需要參考的參數列表中提供的所有參數。例如。下面的代碼在運行時會導致一個bug,因爲格式化字符串中第一個位置參數是未使用的:'[NSString stringWithFormat:@「%2 $ @」,@「bar」,@「foo」]' - 請參閱http: //stackoverflow.com/questions/2946649/nsstring-stringwithformat-swizzled-to-allow-missing-format-numbered-args – mrb 2012-07-12 14:44:47

+1

@mrb對。這是C中可變參數('...')實現的副作用(不是bug)。如果你沒有告訴格式化函數什麼類型的參數(通過引用它至少一次),沒有辦法在它之後正確地找到它們。 – hamstergene 2012-07-12 14:49:05

+0

我用predicateWithFormat嘗試它,但不工作。如何使用謂詞的參數位置? – Add080bbA 2015-07-14 16:28:14