首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

iOS 字串格式化錯誤:無效轉換符號 $ 的解決方法

     編輯:程式設計綜合問答

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

避免建議

  • 熟悉 Apple 官方格式規範文檔
  • 使用編輯器的語法高亮檢查格式字串
  • 複雜格式化優先使用 NSNumberFormatter、NSDateFormatter 等專用類別
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved