宏(Macro)在 iOS 開發中扮演著「少寫重複程式碼」的角色。用得好,不僅判斷式變短、可讀性提升,專案規模一大之後維護成本也會明顯下降。以下依用途分類,整理一批實戰中反覆用到的常用宏,後續仍會持續補充。
這一組宏主要解決「空值判斷」和「取得環境資訊」兩類瑣事,幾乎每個專案都會用到。
// 字符串是否為空
#define kStringIsEmpty(str) ([str isKindOfClass:[NSNull class]] || str == nil || [str length] < 1 ? YES : NO )
// 數組是否為空
#define kArrayIsEmpty(array) (array == nil || [array isKindOfClass:[NSNull class]] || array.count == 0)
// 字典是否為空
#define kDictIsEmpty(dic) (dic == nil || [dic isKindOfClass:[NSNull class]] || dic.allKeys == 0)
// 是否為空對象(同時涵蓋 length 與 count 兩類容器)
#define kObjectIsEmpty(_object) (_object == nil \
|| [_object isKindOfClass:[NSNull class]] \
|| ([_object respondsToSelector:@selector(length)] && [(NSData *)_object length] == 0) \
|| ([_object respondsToSelector:@selector(count)] && [(NSArray *)_object count] == 0))
// 螢幕寬度
#define kScreenWidth \
([[UIScreen mainScreen] respondsToSelector:@selector(nativeBounds)] ? [UIScreen mainScreen].nativeBounds.size.width/[UIScreen mainScreen].nativeScale : [UIScreen mainScreen].bounds.size.width)
// 螢幕高度
#define kScreenHeight \
([[UIScreen mainScreen] respondsToSelector:@selector(nativeBounds)] ? [UIScreen mainScreen].nativeBounds.size.height/[UIScreen mainScreen].nativeScale : [UIScreen mainScreen].bounds.size.height)
// 螢幕尺寸
#define kScreenSize \
([[UIScreen mainScreen] respondsToSelector:@selector(nativeBounds)] ? CGSizeMake([UIScreen mainScreen].nativeBounds.size.width/[UIScreen mainScreen].nativeScale,[UIScreen mainScreen].nativeBounds.size.height/[UIScreen mainScreen].nativeScale) : [UIScreen mainScreen].bounds.size)
// 常見單例的縮寫
#define kApplication [UIApplication sharedApplication]
#define kKeyWindow [UIApplication sharedApplication].keyWindow
#define kAppDelegate [UIApplication sharedApplication].delegate
#define kUserDefaults [NSUserDefaults standardUserDefaults]
#define kNotificationCenter [NSNotificationCenter defaultCenter]
// App 版本號
#define kAppVersion [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"]
// 系統版本號
#define kSystemVersion [[UIDevice currentDevice] systemVersion]
// 當前語言
#define kCurrentLanguage ([[NSLocale preferredLanguages] objectAtIndex:0])
// 是否為 iPhone / iPad
#define kISiPhone (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
#define kISiPad (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
// 沙盒路徑
#define kDocumentPath [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject]
#define kTempPath NSTemporaryDirectory()
#define kCachePath [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject]
// 真機 / 模擬器判斷
#if TARGET_OS_IPHONE
// 真機
#endif
#if TARGET_IPHONE_SIMULATOR
// 模擬器
#endif
// 只在 Debug 下輸出的 NSLog,Release 版本自動清空
#ifdef DEBUG
#define NSLog(...) NSLog(@"%s 第%d行 \n %@\n\n",__func__,__LINE__,[NSString stringWithFormat:__VA_ARGS__])
#else
#define NSLog(...)
#endif
// 顏色相關
#define kRGBColor(r, g, b) [UIColor colorWithRed:(r)/255.0 green:(g)/255.0 blue:(b)/255.0 alpha:1.0]
#define kRGBAColor(r, g, b, a) [UIColor colorWithRed:(r)/255.0 green:(g)/255.0 blue:(b)/255.0 alpha:a]
#define kRandomColor KRGBColor(arc4random_uniform(256)/255.0,arc4random_uniform(256)/255.0,arc4random_uniform(256)/255.0)
#define kColorWithHex(rgbValue) \
[UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16)) / 255.0 \
green:((float)((rgbValue & 0xFF00) >> 8)) / 255.0 \
blue:((float)(rgbValue & 0xFF)) / 255.0 alpha:1.0]
// 弱引用 / 強引用成對使用,避免 block 迴圈引用
#define kWeakSelf(type) __weak typeof(type) weak##type = type;
#define kStrongSelf(type) __strong typeof(type) type = weak##type;
// 角度與弧度互轉
#define kDegreesToRadian(x) (M_PI * (x) / 180.0)
#define kRadianToDegrees(radian) (radian * 180.0) / (M_PI)
// 計時
#define kStartTime CFAbsoluteTime start = CFAbsoluteTimeGetCurrent();
#define kEndTime NSLog(@"Time: %f", CFAbsoluteTimeGetCurrent() - start)
其中 kWeakSelf / kStrongSelf 這對組合特別值得推薦,它用 typeof 保留原變數型別,在 block 內先弱後強,是對抗循環參照最省事的寫法。
把狀態欄、導航欄這些系統固定高度集中管理,之後要調整就不必全專案搜尋。
// 狀態欄高度 #define STATUS_BAR_HEIGHT 20 // 導航欄高度 #define NAVIGATION_BAR_HEIGHT 44 // 狀態欄 + 導航欄 #define STATUS_AND_NAVIGATION_HEIGHT ((STATUS_BAR_HEIGHT) + (NAVIGATION_BAR_HEIGHT)) // 螢幕相關 #define SCREEN_RECT ([UIScreen mainScreen].bounds) #define SCREEN_WIDTH ([UIScreen mainScreen].bounds.size.width) #define SCREEN_HEIGHT ([UIScreen mainScreen].bounds.size.height) #define CONTENT_HEIGHT (SCREEN_HEIGHT - NAVIGATION_BAR_HEIGHT - STATUS_BAR_HEIGHT) // 螢幕解析度 #define SCREEN_RESOLUTION (SCREEN_WIDTH * SCREEN_HEIGHT * ([UIScreen mainScreen].scale)) // 業務自訂高度 #define BANNER_HEIGHT 215 #define STYLEPAGE_HEIGHT 21 #define SMALLTV_HEIGHT 77 #define SMALLTV_WIDTH 110 #define FOLLOW_HEIGHT 220 #define SUBCHANNEL_HEIGHT 62
把常用的 Documents、Caches、tmp 路徑,以及基於它們衍生的檔案位置一併集中,讀檔寫檔時就乾淨多了。
// 目錄 #define kPathTemp NSTemporaryDirectory() #define kPathDocument [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] #define kPathCache [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0] // 具體檔案 #define kPathSearch [kPathDocument stringByAppendingPathComponent:@"Search.plist"] #define kPathMagazine [kPathDocument stringByAppendingPathComponent:@"Magazine"] #define kPathDownloadedMgzs [kPathMagazine stringByAppendingPathComponent:@"DownloadedMgz.plist"] #define kPathDownloadURLs [kPathMagazine stringByAppendingPathComponent:@"DownloadURLs.plist"] #define kPathOperation [kPathMagazine stringByAppendingPathComponent:@"Operation.plist"] #define kPathSplashScreen [kPathCache stringByAppendingPathComponent:@"splashScreen"]
這一組涵蓋日誌、系統版本比較、顏色、時間戳等,是日常開發呼叫頻率最高的部分。
// 日誌:ALog 全版本輸出 #define ALog(fmt, ...) NSLog((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__); #ifdef DEBUG #define DLog(fmt, ...) NSLog((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__); #else #define DLog(...) #endif #ifdef DEBUG #define ULog(...) // 需要彈窗除錯時可改成 UIAlertView 版本 #else #define ULog(...) #endif // 系統版本比較 #define SYSTEM_VERSION_EQUAL_TO(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedSame) #define SYSTEM_VERSION_GREATER_THAN(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedDescending) #define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending) #define SYSTEM_VERSION_LESS_THAN(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedAscending) #define SYSTEM_VERSION_LESS_THAN_OR_EQUAL_TO(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedDescending) // RGB / RGBA 顏色 #define RGBA(r,g,b,a) [UIColor colorWithRed:r/255.0f green:g/255.0f blue:b/255.0f alpha:a] #define RGB(r,g,b) RGBA(r,g,b,1.0f) // 是否為直向 #define IsPortrait ([UIApplication sharedApplication].statusBarOrientation == UIInterfaceOrientationPortrait || [UIApplication sharedApplication].statusBarOrientation == UIInterfaceOrientationPortraitUpsideDown) // 是否為 nil 或 NSNull #define IsNilOrNull(_ref) (((_ref) == nil) || ([(_ref) isEqual:[NSNull null]])) // 角度轉弧度 #define DEGREES_TO_RADIANS(d) (d * M_PI / 180) // 版本捷徑 #define iOS7_OR_LATER SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"7.0") #define iOS8_OR_LATER SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"8.0") // iOS7 之下,導航控制器內 view 的起始高度 #define YH_HEIGHT (iOS7_OR_LATER ? 64 : 0) // 取得 10 位時間戳 #define getCurentTime [NSString stringWithFormat:@"%ld", (long)[[NSDate date] timeIntervalSince1970]]
把通知名稱抽成宏,最大的好處是「拼字錯誤」在編譯階段就會被抓出來,而不是等到 runtime 收不到通知才發現。
// 取消收藏 #define TNCancelFavoriteProductNotification @"TNCancelFavoriteProductNotification" // 標記收藏 #define TNMarkFavoriteProductNotification @"TNMarkFavoriteProductNotification" // 下載進度變化 #define kNotficationDownloadProgressChanged @"kNotficationDownloadProgressChanged" // 暫停下載 #define kNotificationPauseDownload @"kNotificationPauseDownload" // 開始下載 #define kNotificationStartDownload @"kNotificationStartDownload" // 下載成功 #define kNotificationDownloadSuccess @"kNotificationDownloadSuccess" // 下載失敗 #define kNotificationDownloadFailed @"kNotificationDownloadFailed" // 下載新刊物 #define kNotificationDownloadNewMagazine @"kNotificationDownloadNewMagazine"
把環境切換與介面路徑集中,正式包與測試包只有一行之差,不容易出包出錯環境。
#ifdef DEBUG // Debug:測試環境 #define API_BASE_URL_STRING @"https://boys.test.companydomain.com/api/" #else // Release:正式環境 #define API_BASE_URL_STRING @"https://www.companydomain.com/api/" #endif // 介面路徑 #define GET_CONTENT_DETAIL @"channel/getContentDetail" // 取得內容詳情(含上一篇與下一篇) #define GET_COMMENT_LIST @"comment/getCommentList" // 取得評論列表 #define COMMENT_LOGIN @"comment/login" // 評論需先登入 #define COMMENT_PUBLISH @"comment/publish" // 發布評論 #define COMMENT_DELETE @"comment/delComment" // 刪除評論 #define LOGINOUT @"common/logout" // 登出
宏一多,檔案就會跟著變多。實務上建議再建一個總入口 Macros.h 把它們全部彙整,然後只在專案的 pch 檔裡引入一次,全專案即可直接使用。
// Macros.h #import "UtilsMacros.h" #import "APIStringMacros.h" #import "DimensMacros.h" #import "NotificationMacros.h" #import "SharePlatformMacros.h" #import "StringMacros.h" #import "UserBehaviorMacros.h" #import "PathMacros.h"
// XcodeProjectName-Prefix.pch #ifdef __OBJC__ #import <UIKit/UIKit.h> #import <Foundation/Foundation.h> #import "Macros.h" #endif
除了上述幾類,實際專案裡常見的還有分享平台列舉、字串處理、使用者行為埋點等模組,可以依團隊慣例自行擴充。宏整理是一份會持續長大的清單,後續再補充。