1 选择工程的Target -> Build Settings -> Preprocessor Macros.xcode
如图,默认 Debug项,是“DEBUG=1”.app
2 在程序中设置全局宏定义函数
在程序的 ApplicationName-Prefix.pch 文件中,加入以下,很简单工具
#ifdef DEBUG_MODE #define DLog( s, ... ) NSLog( @"<%p %@:(%d)> %@", self, [[NSString stringWithUTF8String:__FILE__] lastPathComponent], __LINE__, [NSString stringWithFormat:(s), ##__VA_ARGS__] ) #else #define DLog( s, ... ) #endif
3 这样就设置好了,测试开发工具
在任意ViewController.m中写入 测试
DLog(@"1234");
结果:ui
2012-07-25 17:09:54.448 xxxx[7094:707] <0x28f790 ViewController.m:(64)> 1234
这样发布的时候DLog就不会有输出了。 spa
在Objective-c开发程序的时候,有专门的日志操做类NSLog,它将指定的输出,输出到(stderr),咱们能够利用Xcode的日志输出窗口,那么既然是要记录到具体日志文件,咱们就想输出日志写入到具体的日志文件便可。
代码
一、 宏定义(下面是我在程序中经常使用到的日志宏,用DEBUG开关管理,
也就是说只有在DEBUG模式下才让日志输出 :)
#ifdef DEBUG
# define LOG(fmt, ...) do { \
NSString* file = [[NSString alloc] initWithFormat:@"%s", __FILE__]; \
NSLog((@"%@(%d) " fmt), [file lastPathComponent], __LINE__, ##__VA_ARGS__); \
[file release]; \
} while(0)
# define LOG_METHOD NSLog(@"%s", __func__)
# define LOG_CMETHOD NSLog(@"%@/%@", NSStringFromClass([self class]), NSStringFromSelector(_cmd))
# define COUNT(p) NSLog(@"%s(%d): count = %d\n", __func__, __LINE__, [p retainCount]);
# define LOG_TRACE(x) do {printf x; putchar('\n'); fflush(stdout);} while (0)
#else
# define LOG(...)
# define LOG_METHOD
# define LOG_CMETHOD
# define COUNT(p)
# define LOG_TRACE(x)
#endif
能够看到,除了标准的用户定义输出外,我还加入了许多有用的信息,
好比源程序文件位置,行号,类名,函数名等。具体的应用能够在具体的开发过程当中添加、删除。
二、 应用:
- (void)redirectNSLogToDocumentFolder{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fileName =[NSString stringWithFormat:@"%@.log",[NSDate date]];
NSString *logFilePath = [documentsDirectory stringByAppendingPathComponent:fileName];
freopen([logFilePath cStringUsingEncoding:NSASCIIStringEncoding],"a+",stderr);
}
- (void)applicationDidFinishLaunching:(UIApplication *)application {
// 真机测试时保存日志
if ([CDeviceInfo getModelType] != SIMULATOR) {
[self redirectNSLogToDocumentFolder];
}
}
真机测试的时候,能够利用freopen将标准错误输出保存到指定的文件当中,
这样就能够在问题发生后分析日志文件。
三、 设置DEBUG标志是否正肯定义
Xcode 通常会在 debug 运行配置项里面已经定义号了DEBUG 标志,若是没定义咱们就本身写上,以个人 Xcode 4 为例,在项目get Info中找到 PreProcessor Macros 这个属性,对于 Debug 配置咱们给他写上 DEBUG,而在 Release 配置中把它留空。 这样咱们刚才那段预处理命令就能够根据这个标志来判断咱们编译的时调试版本仍是发布版本,从而控制 NSLog 的输出。 (由于 Xcode 4 会把 debug/release 两个配置项同时对比展示出来,而 3.x 版本的只能分别设置,若是你用的时xcode 3.x 开发工具, 那么就分别对 Debug/Release 都检查一下)。debug