把重複出現的判斷、取色、日誌語句抽成宏,能顯著提升代碼可讀性與維護效率。以下是一份可直接放入 PrefixHeader.pch 的常用宏集合。
#define SCREEN_WIDTH ([UIScreen mainScreen].bounds.size.width) #define SCREEN_HEIGHT ([UIScreen mainScreen].bounds.size.height) #define WIDTH [[UIScreen mainScreen] bounds].size.width #define HEIGHT [[UIScreen mainScreen] bounds].size.height #define SAFE_RELEASE(x) [x release]; x = nil #define IOS_VERSION [[[UIDevice currentDevice] systemVersion] floatValue] #define CurrentSystemVersion ([[UIDevice currentDevice] systemVersion]) #define CurrentLanguage ([[NSLocale preferredLanguages] objectAtIndex:0])
#define BACKGROUND_COLOR [UIColor colorWithRed:242.0/255.0 green:236.0/255.0 blue:231.0/255.0 alpha:1.0] #define RGBCOLOR(r, g, b) [UIColor colorWithRed:(r)/255.0f green:(g)/255.0f blue:(b)/255.0f alpha:1] #define RGBACOLOR(r, g, b, a) [UIColor colorWithRed:(r)/255.0f green:(g)/255.0f blue:(b)/255.0f alpha:(a)]
#ifdef DEBUG # define DLog(fmt, ...) NSLog((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__); #else # define DLog(...) #endif
這段宏的妙處在於自動帶出函數名與行號,Release 包裡又會被編譯器完全消除,不產生任何開銷。
#define isRetina ([UIScreen instancesRespondToSelector:@selector(currentMode)] \
? CGSizeEqualToSize(CGSizeMake(640, 960), [[UIScreen mainScreen] currentMode].size) : NO)
#define iPhone5 ([UIScreen instancesRespondToSelector:@selector(currentMode)] \
? CGSizeEqualToSize(CGSizeMake(640, 1136), [[UIScreen mainScreen] currentMode].size) : NO)
#define isPad (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
這種通過分辨率判斷機型的方式在 Retina 與非 Retina 並存的年代很流行,但 iPhone 6 之後分辨率多樣化,已不適用。現代做法應基於 UIScreen.mainScreen.bounds 換算的邏輯點尺寸,或使用 UIDevice 的 userInterfaceIdiom 配合 Auto Layout 自適應。
#if TARGET_OS_IPHONE
// 運行於 iOS 設備
#endif
#if TARGET_IPHONE_SIMULATOR
// 運行於模擬器
#endif
#if __has_feature(objc_arc)
// 使用 ARC 編譯
#else
// 未使用 ARC
#endif
#define BACK(block) dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), block) #define MAIN(block) dispatch_async(dispatch_get_main_queue(), block) #define USER_DEFAULT [NSUserDefaults standardUserDefaults] #define degreesToRadian(x) (M_PI * (x) / 180.0) #define radianToDegrees(radian) ((radian) * 180.0 / M_PI)
宏沒有類型檢查,參數若帶副作用(如 RGBCOLOR(a++, b, c))會被展開多次而產生錯誤,因此宏參數一律加括號是必要習慣。同時,宏不宜過量——把只在一處使用的邏輯也抽成宏,反而降低可讀性。可考慮用 static inline 函數替代簡單計算型宏,既保留性能又具備類型安全。