2013年5月9日 星期四

[iOS] print Log

Because We will need a lot of  information to debug,
so we can use NSLog to print log.

However, these log information we do not want are still being printed out after the release,
we can define like below in project-Prefix.pch:
1
2
3
4
5
6
7
8
//enable NSLogs
#define DEBUG_MODE
#ifdef DEBUG_MODE
    #define DLog(...) NSLog(__VA_ARGS__)
#else
    #define DLog(...) 
#endif
#define ALog(...) NSLog(__VA_ARGS__)
Then use DLog to replace NSLog which one you want control it will be printed or not,
use ALog to replace the one you want always be printed.

When you dont need printed DLog,
 just comment this line #define DEBUG_MODE.




---------------------- By the way below is something about NSLog's usage -----------------------

In order to track bug occurred,
We can add below at each important function:

- (IBAction)showRangeList:(id)sender {
    DLog(@"%s Enter", __func__);
}
When APP executed to this line will print:
-[MainViewController showRangeList:] Enter



And NSLog already provide format,
so we don't need code like this:

NSLog(@"%@",[NSString stringWithFormat:@"%@ %@, %@", 
       errorMsgFormat, 
       error, 
       [error userInfo]]);
just need:

NSLog(@"%@ %@, %@", 
   errorMsgFormat, 
   error, 
   [error userInfo]);
if we only code:

NSLog([NSString stringWithFormat:@"msg:%@",msg]);
Although it's no problem when execute, but there will be a "format not a string literal and no format arguments" warning.

[iOS] Log的使用

開發APP時為了debug需要大量的資訊,
可以使用NSLog打印Log。

然而這些Log資訊我們並不想在發佈後仍被印出來,
可在 project-Prefix.pch 中用以下code將NSLog作一個中介的define:
1
2
3
4
5
6
7
8
//enable NSLogs
#define DEBUG_MODE
#ifdef DEBUG_MODE
    #define DLog(...) NSLog(__VA_ARGS__)
#else
    #define DLog(...) 
#endif
#define ALog(...) NSLog(__VA_ARGS__)
之後想看情況印的NSLog用DLog取代,
總是要印出的就用ALog取代。
這樣當不想印出DLog時就把 #define DEBUG_MODE 註解掉就行了。





----------------------以下順便提一下NSLog用法-----------------------

為了方便追蹤bug發生地點,
可於每個重要function加入:

- (IBAction)showRangeList:(id)sender {
    DLog(@"%s Enter", __func__);
}
這樣執行至此行時便會打印出如下資訊
-[MainViewController showRangeList:] Enter


另外NSLog本身有format功能
因此不需要寫成

NSLog(@"%@",[NSString stringWithFormat:@"%@ %@, %@", 
       errorMsgFormat, 
       error, 
       [error userInfo]]);
只需要

NSLog(@"%@ %@, %@", 
   errorMsgFormat, 
   error, 
   [error userInfo]);
即可。
若是只寫

NSLog([NSString stringWithFormat:@"msg:%@",msg]);
則雖然編譯沒問題但會出現"format not a string literal and no format arguments"的warning。