宏定義能把重複的樣板程式碼收攏到一處,也能讓編譯期就完成許多判斷。以下是我日常累積的常用清單,附上使用情境與該注意的陷阱。
#ifdef DEBUG
#define NSLog(FORMAT, ...) fprintf(stderr, "%s:%d\t%s\n", \
[[[NSString stringWithUTF8String:__FILE__] lastPathComponent] UTF8String], \
__LINE__, \
[[NSString stringWithFormat:FORMAT, ##__VA_ARGS__] UTF8String]);
#else
#define NSLog(FORMAT, ...) nil
#endif這個寫法額外輸出了檔名與行號,對排查問題很有效率;正式包則直接把日誌吃掉。
#ifdef __OBJC__
// 在此引入標頭檔
#endif#define WS(weakSelf) __weak __typeof(&*self) weakSelf = self;
搭配 strongSelf 使用,是處理 block 循環參照最省字角的寫法。
#define ScreenWidth [[UIScreen mainScreen] bounds].size.width #define ScreenHeight [[UIScreen mainScreen] bounds].size.height
#define IOS8UP ([[UIDevice currentDevice].systemVersion floatValue] >= 8)
要提醒的是,用 floatValue 比版本號並不可靠——「8.10」會被解析成小於「8.2」。嚴肅的版本判斷請改用 NSFoundationVersionNumber 或 @available。
#define RGB(a, b, c) [UIColor colorWithRed:(a / 255.0) green:(b / 255.0) blue:(c / 255.0) alpha:1.0] #define RGBA(a, b, c, d) [UIColor colorWithRed:(a / 255.0) green:(b / 255.0) blue:(c / 255.0) alpha:d]
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000
#define SCREEN_WIDTH ([[UIScreen mainScreen] respondsToSelector:@selector(nativeBounds)] ? \
[UIScreen mainScreen].nativeBounds.size.width / [UIScreen mainScreen].nativeScale : \
[UIScreen mainScreen].bounds.size.width)
#define SCREEN_HEIGHT ([[UIScreen mainScreen] respondsToSelector:@selector(nativeBounds)] ? \
[UIScreen mainScreen].nativeBounds.size.height / [UIScreen mainScreen].nativeScale : \
[UIScreen mainScreen].bounds.size.height)
#define SCREEN_SIZE ([[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)
#else
#define SCREEN_WIDTH [UIScreen mainScreen].bounds.size.width
#define SCREEN_HEIGHT [UIScreen mainScreen].bounds.size.height
#define SCREEN_SIZE [UIScreen mainScreen].bounds.size
#endif#define LRRandomColor [UIColor colorWithRed:arc4random_uniform(256) / 255.0 \
green:arc4random_uniform(256) / 255.0 \
blue:arc4random_uniform(256) / 255.0 \
alpha:1.0]#define LRViewBorderRadius(View, Radius, Width, Color) \
[View.layer setCornerRadius:(Radius)]; \
[View.layer setMasksToBounds:YES]; \
[View.layer setBorderWidth:(Width)]; \
[View.layer setBorderColor:[Color CGColor]];#define kGetImage(imageName) [UIImage imageNamed:[NSString stringWithFormat:@"%@", imageName]]
#define LRCurrentLanguage ([[NSLocale preferredLanguages] objectAtIndex:0])
// 是否為 iPhone
#define IS_IPHONE (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
// 是否為 iPad
#define IS_IPAD (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
// 是否為 iPod
#define IS_IPOD ([[[UIDevice currentDevice] model] isEqualToString:@"iPod touch"])
// 是否為 iPhone 5SE
#define iPhone5SE ([[UIScreen mainScreen] bounds].size.width == 320.0f && \
[[UIScreen mainScreen] bounds].size.height == 568.0f)
// 是否為 iPhone 6 / 6s
#define iPhone6_6s ([[UIScreen mainScreen] bounds].size.width == 375.0f && \
[[UIScreen mainScreen] bounds].size.height == 667.0f)
// 是否為 iPhone 6Plus / 6sPlus
#define iPhone6Plus_6sPlus ([[UIScreen mainScreen] bounds].size.width == 414.0f && \
[[UIScreen mainScreen] bounds].size.height == 736.0f)
// 系統版本
#define IOS_SYSTEM_VERSION [[[UIDevice currentDevice] systemVersion] floatValue]#if TARGET_OS_IPHONE // 真機 #endif #if TARGET_IPHONE_SIMULATOR // 模擬器 #endif
// tmp #define kPathTemp NSTemporaryDirectory() // Documents #define kPathDocument [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] // Caches #define kPathCache [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject]
很多人定義常量字串時習慣用宏,最典型的例子就是伺服器位址。但其實這種情境更適合用 const。差異如下:
結論:定義常量字串用 const,定義程式碼片段用宏。
static NSString * const loginAccount = @"loginAccount"; static NSString * const loginPassword = @"loginPassword";
// SynthesizeSingleton.h
#ifndef SynthesizeSingleton_h
#define SynthesizeSingleton_h
// 宣告
#define DECLARE_SYNTHESIZE_SINGLETON_FOR_CLASS(classname) \
+ (classname *)sharedInstance;
// 實作
#define IMPLEMENT_SYNTHESIZE_SINGLETON_FOR_CLASS(classname) \
static classname *shared##classname = nil; \
+ (classname *)sharedInstance { \
@synchronized(self) { \
if (shared##classname == nil) { \
shared##classname = [[self alloc] init]; \
} \
} \
return shared##classname; \
} \
+ (id)allocWithZone:(NSZone *)zone { \
@synchronized(self) { \
if (shared##classname == nil) { \
shared##classname = [super allocWithZone:zone]; \
return shared##classname; \
} \
} \
return nil; \
} \
- (id)copyWithZone:(NSZone *)zone { \
return self; \
}
#endif使用方式是在需要單例的類的 .h 與 .m 中分別寫入(記得先引入上面的標頭檔):
// ViewController.h @interface ViewController : UIViewController SingletonH(viewController) @end // ViewController.m @implementation ViewController SingletonM(ViewController) @end
宏不是萬靈丹。它有幾個先天限制值得知道:因為是純文字替換,除錯時看不到型別資訊,出錯訊息也往往指向展開後的位置而非你寫的那一行;而且宏沒有作用域概念,容易與其他標頭檔的定義撞名。近幾年 Swift 上線後,型別安全的 let 常數、計算屬性與全域變數已經能取代絕大多數場景,如果你在寫純 Swift 專案,這份清單的適用範圍會小很多。
本文整理自「上吊的豆腐」於簡書發佈的相關文章。