注:宏的使用可以节省代码重复输入工作,还可以为调试带来各种好处。本文列出了几个非常简单实用的宏。

 

这些是我在Xcode中常用到的宏:

 

CMLog: 用它来代替NSLog:

1
#define CMLog(format, ...) NSLog(@"%s:%@", __PRETTY_FUNCTION__,[NSString stringWithFormat:format, ## __VA_ARGS__]);

 

它的作用是将调用它的类和方法的名称一起输出到控制台。比如你在MyAppDelegate类的applicationDidFinishLaunching方法中调用它:

1
CMLog(@"My iPhone is an %@, v %@", [[UIDevice currentDevice] model], [[UIDevice currentDevice] systemVersion]);

 

控制台将输出:

2009-01-05 10:06:28.957 MyApp15173:20b] -[MyAppDelegate applicationDidFinishLaunching:]:
My iPhone is an iPhone Simulator, v 2.2

 

MARK: 此宏用于输出调用它的类和方法名称。适用于只想知道是否一个方法被调用了。

1
#define MARK    CMLog(@"%s", __PRETTY_FUNCTION__);

 

START_TIMEREND_TIMER: 用于确定一个方法或一段代码的运行时间:

1
2
#define START_TIMER NSTimeInterval start = [NSDate timeIntervalSinceReferenceDate];  
#define END_TIMER(msg)  NSTimeInterval stop = [NSDate timeIntervalSinceReferenceDate]; CMLog([NSString stringWithFormat:@"%@ Time = %f";, msg, stop-start]);

 

START_TIMER 置于需评测的代码段开始处,并将END_TIMER置于代码段结束处,你就可获得这段代码的运行时间:

1
2
3
4
5
6
7
- (NSData *)loadDataFromURL:(NSString *)dataURL  
{    
    START_TIMER;    
    NSData *data = [self doSomeStuff:dataURL];    
    END_TIMER(@"loadDataFromURL");    
    return data;  
}

 

输出为:

2009-01-05 10:31:37.943 MyApp[15283:20b] -[MyAppDelegate loadDataFromURL:]:
loadDataFromURL Time = 3.636021  

 

将所有这些宏定义整理使用条件标志放在预编译的头文件中。调试时,此标志设为1 ,发布时将其设为0 。

1
2
3
4
5
6
7
8
9
10
#if DEBUG==1  
    #define CMLog(format, ...) NSLog(@"%s:%@";, __PRETTY_FUNCTION__,[NSString stringWithFormat:format, ## __VA_ARGS__]);  
    #define MARK    CMLog(@"%s";, __PRETTY_FUNCTION__);  
    #define START_TIMER NSTimeInterval start = [NSDate timeIntervalSinceReferenceDate];  
    #define END_TIMER(msg)  NSTimeInterval stop = [NSDate timeIntervalSinceReferenceDate]; CMLog([NSString stringWithFormat:@"%@ Time = %f";, msg, stop-start]);  
#else  
    #define CMLog(format, ...)  
    #define MARK  #define START_TIMER  
    #define END_TIMER(msg)  
#endif

 

Debug目标设定中加入:

OTHER_CFLAGS = -DDEBUG=1  

 

Release 目标设定中加入:

OTHER_CFLAGS = -DDEBUG=0

 

原文见:Macros for Xcode