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

IOS 開發中常用的宏定義

編輯:iOS 開發綜合

在 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]

自訂 Log

#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; \
}

宏雖然方便,但過度使用會降低可讀性,建議只針對固定且不常變動的設定使用。

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