做 iOS 專案久了,總會累積一批「每次都要重打一次」的巨集。這篇把日常開發最常用到的定義依用途分類整理,包含判空、裝置與螢幕尺寸、沙盒路徑、日誌開關、顏色轉換、記憶體管理與單例等,需要的時候直接複製貼上即可。
伺服器回傳的資料最不可信,特別是 JSON 裡的 NSNull,若不先擋掉很容易閃退。
#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))
反斜線是行接續符號,用來把多行寫成一個巨集。取尺寸時優先使用 nativeBounds 並除以 nativeScale,可以得到與鎖定方向無關的實際解析度:
#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 SCREEN_WIDTH ([UIScreen mainScreen].bounds.size.width) #define SCREEN_HEIGHT ([UIScreen mainScreen].bounds.size.height)
判斷機型與裝置:
#define isPad (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) #define kISiPhone (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) #define kISiPad (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) #define NavigationBar_HEIGHT 44 // 真機 / 模擬器 #if TARGET_OS_IPHONE // iPhone Device #endif #if TARGET_IPHONE_SIMULATOR // iPhone Simulator #endif
#define kApplication [UIApplication sharedApplication] #define kKeyWindow [UIApplication sharedApplication].keyWindow #define kAppDelegate [UIApplication sharedApplication].delegate #define kUserDefaults [NSUserDefaults standardUserDefaults] #define kNotificationCenter [NSNotificationCenter defaultCenter] #define kAppVersion [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"] #define kSystemVersion [[UIDevice currentDevice] systemVersion] #define IOS_VERSION [[UIDevice currentDevice].systemVersion floatValue] #define kCurrentLanguage ([[NSLocale preferredLanguages] objectAtIndex:0])
需要嚴謹的版本比較時,別用字串比大小,改用 NSNumericSearch:
#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)
#define kDocumentPath [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] #define kTempPath NSTemporaryDirectory() #define kCachePath [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject]
最實用的一個:只在 Debug 建置輸出,正式版自動清空,同時印出函式名稱與行號,方便定位。
#ifdef DEBUG # define DLog(fmt, ...) NSLog((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__); #else # define DLog(...) #endif
直接改寫 NSLog 也可以,Release 版本會退化為空操作:
#ifdef DEBUG
# define NSLog(FORMAT, ...) fprintf(stderr, "\nfunction:%s line:%d content:%s\n", \
__FUNCTION__, __LINE__, [[NSString stringWithFormat:FORMAT, ##__VA_ARGS__] UTF8String]);
#else
# define NSLog(FORMAT, ...) nil
#endif
除錯時若想讓訊息直接跳出來(注意 UIAlertView 在新系統已被 UIAlertController 取代,新專案請改用後者):
#ifdef DEBUG
# define ULog(fmt, ...) { UIAlertController *alert = \
[UIAlertController alertControllerWithTitle:[NSString stringWithFormat:@"%s\n[Line %d]", __PRETTY_FUNCTION__, __LINE__] \
message:[NSString stringWithFormat:fmt, ##__VA_ARGS__] preferredStyle:UIAlertControllerStyleAlert]; \
[self presentViewController:alert animated:YES completion:nil]; }
#else
# define ULog(...)
#endif
分級日誌可以搭配門檻控制輸出量,正式環境只留錯誤:
#define ITTLOGLEVEL_INFO 10 #define ITTLOGLEVEL_WARNING 3 #define ITTLOGLEVEL_ERROR 1 #ifdef DEBUG # define ITTMAXLOGLEVEL ITTLOGLEVEL_INFO #else # define ITTMAXLOGLEVEL ITTLOGLEVEL_ERROR #endif #ifdef ITTDEBUG # define ITTDPRINT(xx, ...) NSLog(@"%s(%d): " xx, __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__) #else # define ITTDPRINT(xx, ...) ((void)0) #endif #define ITTDPRINTMETHODNAME() ITTDPRINT(@"%s", __PRETTY_FUNCTION__) #if ITTLOGLEVEL_ERROR <= ITTMAXLOGLEVEL # define ITTDERROR(xx, ...) ITTDPRINT(xx, ##__VA_ARGS__) #else # define ITTDERROR(xx, ...) ((void)0) #endif #if ITTLOGLEVEL_WARNING <= ITTMAXLOGLEVEL # define ITTDWARNING(xx, ...) ITTDPRINT(xx, ##__VA_ARGS__) #else # define ITTDWARNING(xx, ...) ((void)0) #endif #if ITTLOGLEVEL_INFO <= ITTMAXLOGLEVEL # define ITTDINFO(xx, ...) ITTDPRINT(xx, ##__VA_ARGS__) #else # define ITTDINFO(xx, ...) ((void)0) #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)
十六進位色碼轉 UIColor:
#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]
#define UIColorFromRGB(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]
直接用 0–255 的通道值帶入(注意第四个參數是透明度,流傳許久的 kRGBAColor 版本有複製貼上的筆誤,把 G、B 都寫成 r,記得修正):
#define RGB(r, g, b) [UIColor colorWithRed:(r)/255.0f green:(g)/255.0f blue:(b)/255.0f alpha:1.0f] #define RGBA(r, g, b, a) [UIColor colorWithRed:(r)/255.0f green:(g)/255.0f blue:(b)/255.0f alpha:a] #define CLEARCOLOR [UIColor clearColor] #define BACKGROUND_COLOR [UIColor colorWithRed:242.0/255.0 green:236.0/255.0 blue:231.0/255.0 alpha:1.0]
#define LOADIMAGE(file, ext) [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:file ofType:ext]] #define IMAGE(A) [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:A ofType:nil]]
前兩種以檔案內容載入的方式,在大量重複使用的情境下效能通常優於 imageNamed:,後者會走系統快取。
#define kDegreesToRadian(x) (M_PI * (x) / 180.0) #define kRadianToDegrees(x) ((x) * 180.0 / M_PI) #define kStartTime CFAbsoluteTime start = CFAbsoluteTimeGetCurrent(); #define kEndTime NSLog(@"Time: %f", CFAbsoluteTimeGetCurrent() - start)
ARC 與非 ARC 混用的專案,可以用編譯器功能判斷:
#if __has_feature(objc_arc) // compiling with ARC #else // compiling without ARC #endif
非 ARC 下的安全釋放:
#define RELEASE_SAFELY(__POINTER) { [__POINTER release]; __POINTER = nil; }
#define TT_RELEASE_CF_SAFELY(__REF) { if (nil != (__REF)) { CFRelease(__REF); __REF = nil; } }
弱/強引用的成對寫法,避免 block 內的循環參考:
#define kWeakSelf(type) __weak typeof(type) weak##type = type; #define kStrongSelf(type) __strong typeof(type) type = weak##type;
背景執行與回主執行緒:
#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 FONT(F) [UIFont fontWithName:@"FZHTJW--GB1-0" size:F] #define MyLocal(x, ...) NSLocalizedString(x, nil) #define USER_DEFAULT [NSUserDefaults standardUserDefaults] #define APIURL @"https://xxxxx/" #define APILogin [APIURL stringByAppendingString:@"Login"] #define VIEWWITHTAG(_OBJECT, _TAG) [_OBJECT viewWithTag:_TAG]
單例的巨集化寫法(以 @synchronized 保護,並攔住 copy 與 allocWithZone:):
#define SYNTHESIZE_SINGLETON_FOR_CLASS(classname) \
\
static classname *shared##classname = nil; \
\
+ (classname *)shared##classname \
{ \
@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; \
}
建議把這類定義集中放在一個 MacroDefinition.h 並加入 prefix header,全專案就能直接取用:
#ifndef MacroDefinition_h #define MacroDefinition_h // 這裡放你的巨集 #endif
這份清單會持續補充,遇到重複出現的小工具都可以丟進來,長期下來能省掉不少重複打字與 copy-paste 的時間。