今天突然看到一篇文章,介绍了NSLog的使用。NSLog其实不是简单的输出调试信息,还会做一些其他工作,这样在设备上运行的时候会降低效率。
所以优化NSLog就变得非常有必要了。在debug下显示log,在release下自动屏蔽log输出的代码。花了点时间,将网上的两种NSLog优化的方法综合了一下。
具体如下:
一、新建一个.h文件,命名为DLog.h。
DLog.h文件内容为:
//添加定义,在release时不会输出log
#ifndef __OPTIMIZE__
#define NSLog(...) NSLog(__VA_ARGS__)
#else
#define NSLog(...) {}
#endif
#ifndef __OPTIMIZE__
#define DLog(...) NSLog(__VA_ARGS__)
#else
#define DLog(...) /* */
#endif
#define ALog(...) NSLog(__VA_ARGS__)
二、添加到工程。
在appName-Prefix.pch中添加DLog.h头文件。
添加后如下所示:
#import <Availability.h>
#ifndef __IPHONE_3_0
#warning "This project uses features only available in iPhone SDK 3.0 and later."
#endif
#ifdef __OBJC__
#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
#import "DLog.h"
#endif
通过这样定义,既可以用DLog,ALog,也可以使用系统自带的NSLog。
这样就可以在既高效又灵活的使用NSLog了。
参考文章如下:
http://www.cimgf.com/2009/01/24/dropping-nslog-in-release-builds/