1.定義及相關(guān)介紹
宏嘛很簡單疼电,就是簡單的查找替換
分類
- 對象宏(object-like macro):對象宏一般用來定義一些常數(shù)
//對象宏舉例:
#define M_PI 3.14159265358979323846264338327950288
- 函數(shù)宏(function-like macro):就是行為類似函數(shù),可以接受參數(shù)的宏
//A simple function-like macro
#define SELF(x) x
NSString *name = @"Macro Rookie";
NSLog(@"Hello %@",SELF(name));
//輸出:Hello Macro Rookie
//比如系統(tǒng)的MAX,MIN等比較
#if !defined(MAX)
#define __NSMAX_IMPL__(A,B,L) ({ __typeof__(A) __NSX_PASTE__(__a,L) = (A); __typeof__(B) __NSX_PASTE__(__b,L) = (B); (__NSX_PASTE__(__a,L) < __NSX_PASTE__(__b,L)) ? __NSX_PASTE__(__b,L) : __NSX_PASTE__(__a,L); })
#define MAX(A,B) __NSMAX_IMPL__(A,B,__COUNTER__)
#endif
//使用:
NSLog(@"%d",MAX(6, 5));
//輸出:
2016-08-08 15:53:23.827 宏定義的黑魔法[3601:173545] 6
- 函數(shù)宏 VS 靜態(tài)方法
//函數(shù)宏
#define Puls(x,y) (x+y)
//靜態(tài)方法(C語言寫法)
static NSInteger funPlus(CGFloat x,CGFloat y) {
return x + y;
}
NSLog(@"%.2f",My_PI*Puls(3, 5));
NSLog(@"%lu",funPlus(3, 5));
//輸出:
2016-08-08 15:53:23.826 宏定義的黑魔法[3601:173545] 25.13
2016-08-08 15:53:23.827 宏定義的黑魔法[3601:173545] 6
2.實用宏
//debug調(diào)試用
#define NSLogRect(rect) NSLog(@"%s x:%.4f, y:%.4f, w:%.4f, h:%.4f", #rect, rect.origin.x, rect.origin.y, rect.size.width, rect.size.height)
#define NSLogSize(size) NSLog(@"%s w:%.4f, h:%.4f", #size, size.width, size.height)
#define NSLogPoint(point) NSLog(@"%s x:%.4f, y:%.4f", #point, point.x, point.y)
//特別介紹 :該宏的定義场刑,可以有效的打印某行代碼所在的位置
//NSLog信息控制: 1 - 打印信息 0 - 不打印信息
#define ZYDebug 0
#if ZYDebug
#define NSLog(FORMAT, ...) fprintf(stderr,"%s第%d行,Content:%s\n", __FUNCTION__, __LINE__, [[NSString stringWithFormat:FORMAT, ##__VA_ARGS__] UTF8String]);
#else
#define NSLog(FORMAT, ...) nil
#endif
角度轉(zhuǎn)弧度蚪战,弧度轉(zhuǎn)角度
//弧度轉(zhuǎn)角度
#define Radians_To_Degrees(radians) ((radians) * (180.0 / M_PI))
//角度轉(zhuǎn)弧度
#define Degrees_To_Radians(angle) ((angle) / 180.0 * M_PI)
eg:計算三角形的三個點
CGFloat R = 200 ;
CGFloat oirin_y = 100 ;
CGPoint point0 = CGPointMake(self.view.frame.size.width/2.0, 0+oirin_y);
CGPoint point1 = CGPointMake(self.view.frame.size.width/2.0 - R/2.0, cos(Degrees_To_Radians(30))*R + oirin_y);
CGPoint point2 = CGPointMake(self.view.frame.size.width/2.0 + R/2.0, cos(Degrees_To_Radians(30))*R + oirin_y);