原文地址:http://blog.csdn.net/magicZYJ/article/details/51869090
看看很久以前写过的代码,的确过度的使用了宏:
#define BTN_W 60
#define BTN_H 30
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
for (int i = 0; i < 4 ; i++) {
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
btn.frame = CGRectMake(i * BTN_W, 100, BTN_W, BTN_H);
btn.backgroundColor = [UIColor colorWithRed:arc4random() % 256 / 255.f green:arc4random() % 256 / 255.f blue:arc4random() % 256 / 255.f alpha:1];
[self.view addSubview:btn];
}
}
由于宏只是简单的替换,所以每当用到一次的时候,都会创建一个空间去保存这个变量。
取而代之是使用const修饰,使其成为全局常量。使“宏”变为全局常量,在内存中只有一份存储空间。
const CGFloat BTN_W = 60;
const CGFloat BTN_H = 30;
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
for (int i = 0; i < 4 ; i++) {
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
btn.frame = CGRectMake(i * BTN_W, 100, BTN_W, BTN_H);
btn.backgroundColor = [UIColor colorWithRed:arc4random() % 256 / 255.f green:arc4random() % 256 / 255.f blue:arc4random() % 256 / 255.f alpha:1];
[self.view addSubview:btn];
}
}
仅仅使用const修饰的全局常量,在其他文件中也是可以访问到的
extern CGFloat BTN_H;//extern const CGFloat BTN_H
如果不希望其他文件访问,只需再加上static关键字即可。
static const CGFloat BTN_W = 60;
static const CGFloat BTN_H = 30;
为了增强程序的扩展性,可以将这些全局变量 或者 全局常量的引用和定义写到.h和.m文件中。
复杂宏的使用
关键字
… :可变参数
VA_ARGS :宏定义中的…中的所有剩余参数
## :连接符号
# :原样输出
/ :换行符
系统工具方法
COUNTER 无重复的计数器,从程序启动开始每次调用都会++,常用语宏中定义无重复的参数名称
FILE:当前文件的绝对路径,常见于log中
LINE:展开该宏时在文件中的行数,常见于log中
func:所在scope的函数名称,常见于log中