2013年5月9日 星期四

[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。

沒有留言:

張貼留言