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 會(huì)向 ASL 發(fā)送日志信息峡钓,同時(shí)向 Terminal 發(fā)送日志信息痹扇,而且會(huì)出現(xiàn)在Console.app 中谤饭;并且每一次 NSLog 都會(huì)新建一個(gè)ASL client 并向 ASL 守護(hù)進(jìn)程發(fā)起連接,發(fā)送日志信息之后再關(guān)閉連接沥匈。所以說,當(dāng)這個(gè)過程出現(xiàn)N次時(shí)倡缠,就會(huì)消耗大量資源導(dǎo)致程序變慢牵啦。
NSLog的使用場(chǎng)景:
1、輸出存在 Bug 代碼塊的數(shù)據(jù)調(diào)試信息摊腋。
2沸版、輸出定位信息,也是為了便于調(diào)試兴蒸。
可以使用宏自定義一個(gè) log 輸出视粮,減少重復(fù)代碼的編寫。最好在 debug 環(huán)境下使用橙凳。
#ifdef DEBUG
# define DLog(fmt, ...) NSLog((@"[文件名:%s]\n" "[函數(shù)名:%s]\n" "[行號(hào):%d] \n" fmt), __FILE__, __FUNCTION__, __LINE__, ##__VA_ARGS__);
#else
# define DLog(...);
#endif
// __FILE__ 宏在預(yù)編譯時(shí),會(huì)替換成當(dāng)前的源文件名蕾殴。
// __LINE__宏在預(yù)編譯時(shí),會(huì)替換成當(dāng)前的行號(hào)岛啸。
// __FUNCTION__宏在預(yù)編譯時(shí)钓觉,會(huì)替換成當(dāng)前的函數(shù)名稱。