Java 與 C# 都能直接用 + 拼接字串,Objective-C 沒有這個語法糖,得改用 Foundation 提供的方法。以下先假設有兩個已存在的字串 string1 與 string2,目標是把它們連成一個 string。
string = [NSString stringWithFormat:@"%@,%@", string1, string2];
string = [string1 stringByAppendingString:string2];
string = [string stringByAppendingFormat:@"%@,%@", string1, string2];
網路上普遍說法認為第二種效率較佳。實測下差異往往不明顯,實際選擇時還是看情境:需要插入分隔符號或格式化數字時用第一、三種更直觀,純粹兩段相接則用第二種最乾淨。
Objective-C 有個很方便的特性:相鄰的字串常數會被編譯器自動合併。利用這點可以做出可切換環境的 API 位址定義:
// 正式環境 #define API_DOMAIN @"www.jb51.net" // 測試環境 //#define API_DOMAIN @"192.168.0.10" #define API_SYSTEM @"https://"API_DOMAIN@"/system/" #define API_USER @"https://"API_DOMAIN@"/user/"
API_SYSTEM 展開後等於:
@"https://"@"www.jb51.net"@"/system/"
編譯器會把這三段自動接成一個字串常數,完全沒有執行期的效能成本。切換環境時只要改一個 #define,或直接註解切換即可,比在程式碼各處替換安全得多。
若用的是 C 字串而非 NSString,寫法幾乎一樣,只是拿掉 @ 前綴:
#define API_DOMAIN "www.jb51.net" // #define API_DOMAIN "192.168.0.10" #define API_SYSTEM "https://"API_DOMAIN"/system/" #define API_USER "https://"API_DOMAIN"/user/"
小提醒:這種字串常數合併只適用於編譯期就已知的常數,如果想拼接執行期的變數,还是得回到 stringWithFormat: 或 stringByAppendingString: 這幾條路。