合理運用 #define 宏能大幅提升開發效率,下面彙集了一些常用的宏定義。
1、定義常量。定義常量時最好以小寫字母 k 開頭,見名知意。
(1)導航欄高度:iPhone 豎屏時導航欄高度為 44。
#define kNaivgationBarHeight 44
(2)屏幕寬高:屏幕寬高是設備硬件的屏幕尺寸,與 ViewController 的 view 不完全相同。
#define kSCREEN_WIDTH [UIScreen mainScreen].bounds.size.width
#define kSCREEN_HEIGHT [UIScreen mainScreen].bounds.size.height
2、內存管理的安全釋放對象。
#define SAFE_RELEASE(x) [x release];x=nil
注意結尾沒有分號,這條語句在 dealloc 時使用。使用 OC 對象時,最後要保證其引用計數 retainCount 為 0;在 dealloc 中把對象置為 nil,既能釋放內存,又能防止內存洩露。
3、判斷 iOS 系統版本。
(1)當前系統版本號:
#define kCurrentSystemVersion [[[UIDevice currentDevice] systemVersion] floatValue]
(2)判斷是否 iOS 7 或更高:
#define IOS_VERSION_7_OR_LATER (([[[UIDevice currentDevice] systemVersion] floatValue] >=7.0)? (YES):(NO))
(3)當前系統語言:
#define kCurrentLanguage [[NSLocale preferredLanguages] objectAtIndex:0]
4、定義常用顏色。多個控件需設置同一顏色時,用宏定義可省去大量 RGB 代碼。
#define kPurpleColor [UIColor colorWithRed:137.0/255 green:21.0/255 blue:89.0/255 alpha:1.0]
#define kDarkGrayColor [UIColor colorWithRed:100.0/255 green:100.0/255 blue:100.0/255 alpha:1.0]
5、定義比 NSLog 更高級的 DLog。在項目 pch 文件中:
#define DEBUG_MODE 1
#if DEBUG_MODE
#define DLog( s, ... ) NSLog( @"<%p %@:(%d)> %@", self, [[NSString stringWithUTF8String:__FILE__] lastPathComponent], __LINE__, [NSString stringWithFormat:(s), ##__VA_ARGS__] )
#else
#define DLog( s, ... )
#endif
例如在 ViewController 中使用 DLog(@"12345");,控制台會輸出路徑、所在文件與行號等豐富資訊。其中 __FILE__ 定位到文件,__LINE__ 定位到行。
6、判斷是 iPhone 真機還是模擬器。
#if TARGET_OS_IPHONE
NSLog(@"iPhone Device");
#elif TARGET_IPHONE_SIMULATOR
NSLog(@"iPhone Simulator");
#endif
由於模擬器與真機性能不同,這樣判斷很有必要。TARGET_OS_IPHONE 與 TARGET_IPHONE_SIMULATOR 是系統定義的宏,可直接使用。
7、判斷是否是 ARC。
#if __has_feature(objc_arc)
// 使用 arc 編碼
#else
// 使用手動內存管理
#endif
8、定義 GCD 的後台線程與主線程。
//後台運行
#define BACK_GCD(block) dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), block)
//主線程運行
#define MAIN_GCD(block) dispatch_async(dispatch_get_main_queue(),block)