美文网首页
Object-C_宏魔法记录

Object-C_宏魔法记录

作者: 陈胜华 | 来源:发表于2016-08-08 16:11 被阅读21次

1.定义及相关介绍

宏嘛很简单,就是简单的查找替换

分类

  • 对象宏(object-like macro):对象宏一般用来定义一些常数
//对象宏举例:
#define M_PI 3.14159265358979323846264338327950288

  • 函数宏(function-like macro):就是行为类似函数,可以接受参数的宏
//A simple function-like macro 
#define SELF(x) x

NSString *name = @"Macro Rookie"; 
NSLog(@"Hello %@",SELF(name));  
//输出:Hello Macro Rookie

//比如系统的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

  • 函数宏 VS 静态方法

//函数宏
#define Puls(x,y) (x+y)

//静态方法(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调试用
#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

角度转弧度,弧度转角度

//弧度转角度
#define Radians_To_Degrees(radians) ((radians) * (180.0 / M_PI))
//角度转弧度
#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);

相关文章

网友评论

      本文标题:Object-C_宏魔法记录

      本文链接:https://www.haomeiwen.com/subject/vljrsttx.html