[Objective-C语言教程]日志处理(21)

为了打印日志,可使用Objective-C编程语言中的NSLog方法,首先在HelloWorld示例中使用了这个方法。

下面来看一下打印“Hello World”字样的简单代码 -

1 #import <Foundation/Foundation.h>
2 
3 int main() {
4    NSLog(@"Hello, World! \n");
5    return 0;
6 }

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

2018-11-15 09:53:09.761 main[22707] Hello, World!

在实时应用程序中禁用日志

由于在应用程序中经常使用NSLog,它将日志信息打印在设备的日志中,并且在实时构建中打印日志是不好的。 因此,使用类型定义来打印日志,如下所示。

 1 #import <Foundation/Foundation.h>
 2 
 3 #define DEBUG 1
 4 
 5 #if DEBUG == 0
 6 #define DebugLog(...)
 7 #elif DEBUG == 1
 8 #define DebugLog(...) NSLog(__VA_ARGS__)
 9 #endif
10 
11 int main() {
12    DebugLog(@"Debug log, our custom addition gets \
13    printed during debug only" );
14    NSLog(@"NSLog gets printed always" );     
15    return 0;
16 }

执行上面示例代码,得到以下结果:

1 2018-11-15 09:50:28.903 main[11115] Debug log, our custom addition gets printed during debug only
2 2018-11-15 09:50:28.903 main[11115] NSLog gets printed always

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

2018-11-15 09:50:28.903 main[11115] NSLog gets printed always

猜你喜欢

转载自www.cnblogs.com/strengthen/p/10571574.html