Objective-C日志处理



NSLog方法

为了打印日志,我们在Objective-C编程语言中使用NSLog方法,从HelloWorld示例开始我们就一直在使用它。

让我们看一段打印“Hello World”字样的简单代码:

#import <Foundation/Foundation.h>

int main() {
   NSLog(@"Hello, World! \n");
   return 0;
}

现在,当我们编译并运行程序时,我们将得到以下结果。

2013-09-16 00:32:50.888 demo[16669] Hello, World! 

在正式应用中禁用日志

由于我们在应用程序中使用的NSLog会打印在设备的日志中,在正式版本中打印日志并不理想。因此,我们使用类型定义来打印日志,我们可以像下面这样使用它们。

#import <Foundation/Foundation.h>

#if DEBUG == 0
#define DebugLog(...)
#elif DEBUG == 1
#define DebugLog(...) NSLog(__VA_ARGS__)
#endif

int main() {
   DebugLog(@"Debug log, our custom addition gets \
   printed during debug only" );
   NSLog(@"NSLog gets printed always" );     
   return 0;
}

现在,当我们在调试模式下编译并运行程序时,我们将得到以下结果。

2013-09-11 02:47:07.723 demo[618] Debug log, our custom addition gets printed during debug only
2013-09-11 02:47:07.723 demo[618] NSLog gets printed always

现在,当我们在发布模式下编译并运行程序时,我们将得到以下结果。

2013-09-11 02:47:45.248 demo[3158] NSLog gets printed always
广告
© . All rights reserved.