開發時我們常需要在 PCH 中定義一些整個專案都用得到的變數。過去多數人的習慣是直接寫個巨集了事,但如果仔細翻閱 Apple 官方文件,會發現他們定義這類常數時用的是 const 而不是 #define。為什麼?先看 const 的基本行為。
void testConst() {
const int age1 = 20;
int const age2 = 30;
}
這兩種寫法效果完全相同:age1 與 age2 都是唯讀常數,編譯階段就不可再賦值。
關鍵字是「就近原則」:const 靠近誰,誰就變成常數。
void testConst2() {
int age = 20;
// const 修飾的是 *p1 與 *p2
// 也就是說不能透過 p1、p2 間接修改 age 的值
// 但 p1、p2 本身可以改指向別的變數
const int *p1 = &age;
int const *p2 = &age;
p1 = # // 合法:改變指標指向
p2 = # // 合法
// const 修飾的是 p3 本身
// p3 不能再指向其他變數,但可以透過 *p3 改值
int * const p3 = &age;
*p3 = 30; // 合法
// p3 = # // 錯誤:p3 是常數指標
}
把常數集中到一個專屬類別。以通知名稱為例,ZYConst.h:
#import <Foundation/Foundation.h>
// 通知
extern NSString * const ZYEmotionDidSelectNotification;
extern NSString * const ZYSelectEmotionKey;
extern NSString * const ZYEmotionDidDeleteNotification;
ZYConst.m:
#import "ZYConst.h"
NSString * const ZYEmotionDidSelectNotification = @"ZYEmotionDidSelectNotification";
NSString * const ZYSelectEmotionKey = @"ZYSelectEmotionKey";
NSString * const ZYEmotionDidDeleteNotification = @"ZYEmotionDidDeleteNotification";
然後在 PCH 裡引入這個標頭:
#import "ZYConst.h"
整個專案就能共用這組定義了。
用 const 的好處:它在記憶體中只存在一份,無論在專案哪個角落使用都是同一份,型別也受到檢查,因此值得優先採用。
巨集的特性:巨集在編譯期是純文字替換,把定義內容直接插入使用處。使用多次就展開多次,除了容易造成程式碼膨脹,也缺少型別保護。
但有些情況 const 無法取代巨集:
// RGB 顏色
#define ZYColor(r, g, b) [UIColor colorWithRed:(r)/255.0 green:(g)/255.0 blue:(b)/255.0 alpha:1.0]
// 隨機色
#define ZYRandomColor ZYColor(arc4random_uniform(256), arc4random_uniform(256), arc4random_uniform(256))
原因很單純:const 後面接的必須是編譯期就能確定的固定值,而巨集裡帶有參數、需要做計算或函式呼叫的內容,只能仰賴巨集的文字替換機制。結論就是:固定不變的字串與數值用 const,需要帶參數或即時計算的表達式用巨集。