您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 開發常用巨集整理:螢幕尺寸、顏色、日誌與 GCD 語法糖

編輯:iOS 開發綜合

巨集(macro)在 Objective-C 中是消除重複程式碼的利器。把螢幕尺寸、顏色轉換、除錯日誌、GCD 常見寫法都包成巨集,程式碼可讀性會明顯提升。以下依用途分類整理。

尺寸與裝置判斷

#define NavigationBar_HEIGHT 44

#define SCREEN_WIDTH  ([UIScreen mainScreen].bounds.size.width)
#define SCREEN_HEIGHT ([UIScreen mainScreen].bounds.size.height)

#define IOS_VERSION [[[UIDevice currentDevice] systemVersion] floatValue]
#define CurrentSystemVersion ([[UIDevice currentDevice] systemVersion])
#define CurrentLanguage ([[NSLocale preferredLanguages] objectAtIndex:0])

#define isPad (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)

// 舊式(僅供參考,Retina 判斷已無實用意義)
#define isRetina ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(640, 960), [[UIScreen mainScreen] currentMode].size) : NO)
#define iPhone5  ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(640, 1136), [[UIScreen mainScreen] currentMode].size) : NO)

// 編譯環境判斷
#if TARGET_OS_IPHONE
// 真機與模擬器都會進入這裡
#endif

#if TARGET_IPHONE_SIMULATOR
// 僅模擬器
#endif

值得注意的是,iPhone5 這種「用解析度判斷機型」的寫法在/ratio 多樣化之後就不可靠了。要判斷裝置請改用 UIDevice 的 machine 識別碼;要判斷版面請直接用 bounds 或 traitCollection,讓 UI 自己適應。

記憶體管理

#define SAFE_RELEASE(x)      [x release]; x = nil
#define RELEASE_SAFELY(__POINTER) { [__POINTER release]; __POINTER = nil; }

這兩個巨集屬於 MRC 時代的產物。在 ARC 下不需要也不應該呼叫 release,請勿沿用。

ARC 與 GCD

// 是否以 ARC 編譯
#if __has_feature(objc_arc)
// 使用 ARC
#else
// 未使用 ARC
#endif

// GCD 語法糖
#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)

BACK() 與 MAIN() 這類包裝能省下大量重複字元,但要留意:block 內若使用 self 可能造成循環引用,仍 Should 搭配 weak 化身。

顏色

#define RGBCOLOR(r, g, b)       [UIColor colorWithRed:(r)/255.0f green:(g)/255.0f blue:(b)/255.0f alpha:1]
#define RGBACOLOR(r, g, b, a)   [UIColor colorWithRed:(r)/255.0f green:(g)/255.0f blue:(b)/255.0f alpha:(a)]
#define BACKGROUND_COLOR [UIColor colorWithRed:242.0/255.0 green:236.0/255.0 blue:231.0/255.0 alpha:1.0]

角度與弧度轉換

#define degreesToRadian(x)   (M_PI * (x) / 180.0)
#define radianToDegrees(rad) ((rad) * 180.0 / M_PI)

做 transform 旋轉、繪製扇形時很常用。注意巨集參數務必加上括號,否則像 degreesToRadian(a + b) 這種呼叫會因為運算子優先順序而算錯。

日誌

// 只在 Debug 下輸出,Release 自動消除
#ifdef DEBUG
#   define DLog(fmt, ...) NSLog((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__);
#else
#   define DLog(...)
#endif

帶上函式名稱與行號,能省下大量「這行是誰印的」的追尋時間。若要更完整的分級日誌,可以參考下面的版本:

分級日誌系統

#define ITTDEBUG
#define ITTLOGLEVEL_INFO    10
#define ITTLOGLEVEL_WARNING 3
#define ITTLOGLEVEL_ERROR   1

#ifndef ITTMAXLOGLEVEL
#   ifdef DEBUG
#       define ITTMAXLOGLEVEL ITTLOGLEVEL_INFO
#   else
#       define ITTMAXLOGLEVEL ITTLOGLEVEL_ERROR
#   endif
#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

// 條件式日誌
#ifdef ITTDEBUG
#   define ITTDCONDITIONLOG(condition, xx, ...) { if ((condition)) { ITTDPRINT(xx, ##__VA_ARGS__); } } ((void)0)
#else
#   define ITTDCONDITIONLOG(condition, xx, ...) ((void)0)
#endif

// 斷言
#define ITTAssert(condition, ...) \
    do { \
        if (!(condition)) { \
            [[NSAssertionHandler currentHandler] \
                handleFailureInFunction:[NSString stringWithUTF8String:__PRETTY_FUNCTION__] \
                                     file:[NSString stringWithUTF8String:__FILE__] \
                               lineNumber:__LINE__ \
                              description:__VA_ARGS__]; \
        } \
    } while(0)

使用巨集時的三個注意事項

1. 參數要加括號

巨集是純文字替換,不進行型別檢查。參數沒加括號時,SQUARE(a + b) 會展開成 ((a+b)*(a+b)) 之外的東西。養成「參數一律用小括號包住、整個表達式外面再包一層」的習慣。

2. 不要在巨集參數中寫副作用

MAX(i++, j) 可能遞增兩次,因為巨集沒有函式的單次求值保證。

3. 優先考慮 static inline 函式

需要型別安全與除錯資訊時,static inline 函式比巨集更好:有型別檢查、可中斷點、不會重複求值。巨集留給「無法用函式表達」的情境,例如 #ifdef 條件編譯與 __LINE__ 這類編譯期資訊。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved