NSLog 的主要作用:
NSLog does 2 things:
It writes log messages to the Apple System Logging (asl) facility. This allows log messages to show up in Console.app.
It also checks to see if the application's stderr stream is going to a terminal (such as when the application is being run via Xcode). If so it writes the log message to stderr (so that it shows up in the Xcode console).
To send a log message to the ASL facility, you basically open a client connection to the ASL daemon and send the message. But each thread must use a separate client connection. So, to be thread safe, every time NSLog is called it opens a new asl client connection, sends the message, and then closes the connection.
大意为:NSLog 会向 ASL 发送日志信息,同时向 Terminal 发送日志信息,而且会出现在Console.app 中;并且每一次 NSLog 都会新建一个ASL client 并向 ASL 守护进程发起连接,发送日志信息之后再关闭连接。所以说,当这个过程出现N次时,就会消耗大量资源导致程序变慢。
NSLog的使用场景:
1、输出存在 Bug 代码块的数据调试信息。
2、输出定位信息,也是为了便于调试。
可以使用宏自定义一个 log 输出,减少重复代码的编写。最好在 debug 环境下使用。
#ifdef DEBUG
# define DLog(fmt, ...) NSLog((@"[文件名:%s]\n" "[函数名:%s]\n" "[行号:%d] \n" fmt), __FILE__, __FUNCTION__, __LINE__, ##__VA_ARGS__);
#else
# define DLog(...);
#endif
// __FILE__ 宏在预编译时,会替换成当前的源文件名。
// __LINE__宏在预编译时,会替换成当前的行号。
// __FUNCTION__宏在预编译时,会替换成当前的函数名称。