在 iOS 開發中使用 NSString stringWithFormat: 時,若格式字串包含不支援的轉換符號,會導致執行時崩潰並提示「無效轉換符號」。
label1.text = [NSString stringWithFormat:@"%d%$", newvalue1];
%$ 不是 Objective-C 格式化字串的有效轉換符號。常見有效符號包括:
%d、%i - 有符號整數%u - 無符號整數%f - 浮點數%@ - 物件描述%% - 字面百分號若 newvalue1 為整數型別,只需移除錯誤的 %$:
label1.text = [NSString stringWithFormat:@"%d", newvalue1];
若需顯示貨幣符號或特定格式,應使用正確語法:
// 顯示美元符號
label1.text = [NSString stringWithFormat:@"$%d", newvalue1];
// 使用 NSNumberFormatter 進行專業貨幣格式化
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.numberStyle = NSNumberFormatterCurrencyStyle;
formatter.currencyCode = @"USD";
label1.text = [formatter stringFromNumber:@(newvalue1)];
NSNumberFormatter、NSDateFormatter 等專用類別