在 iOS 開發中,適度使用宏可以讓程式碼更簡潔,例如螢幕尺寸、系統版本判斷、顏色轉換與日誌輸出。
#define IOS7 ([[[UIDevice currentDevice].systemVersion doubleValue] >= 7.0)
#define kScreenIphone5 (([[UIScreen mainScreen] bounds].size.height) >= 568)
#define kMainScreenHeight ([UIScreen mainScreen].applicationFrame.size.height)
#define kMainScreenWidth ([UIScreen mainScreen].applicationFrame.size.width)
#define SMSColor(r, g, b) [UIColor colorWithRed:(r)/255.0 green:(g)/255.0 blue:(b)/255.0 alpha:1.0]#ifdef DEBUG
#define SMSLog(...) NSLog(__VA_ARGS__)
#else
#define SMSLog(...)
#endif#define singleton_interface(className) + (className *)shared##className;
#define singleton_implementation(className) \
static className *_instance; \
+ (id)allocWithZone:(struct _NSZone *)zone { \
static dispatch_once_t onceToken; \
dispatch_once(&onceToken, ^{ \
_instance = [super allocWithZone:zone]; \
}); \
return _instance; \
} \
+ (className *)shared##className { \
static dispatch_once_t onceToken; \
dispatch_once(&onceToken, ^{ \
_instance = [[self alloc] init]; \
}); \
return _instance; \
}宏雖然方便,但過度使用會降低可讀性,建議只針對固定且不常變動的設定使用。