ios define NSLog debug 應用發佈nslog註釋

1 選擇工程的Target -> Build Settings -> Preprocessor Macros.xcode

如圖,默認 Debug項,是「DEBUG=1」.app

2 在程序中設置全局宏定義函數

在程序的 ApplicationName-Prefix.pch 文件中,加入以下,很簡單工具

#ifdef DEBUG_MODE
#define DLog( s, ... ) NSLog( @"<%p %@:(%d)> %@", self, [[NSString stringWithUTF8String:__FILE__] lastPathComponent], __LINE__, [NSString stringWithFormat:(s), ##__VA_ARGS__] )
#else
#define DLog( s, ... ) 
#endif


3 這樣就設置好了,測試開發工具

在任意ViewController.m中寫入 測試

DLog(@"1234");

結果:ui

2012-07-25 17:09:54.448 xxxx[7094:707] <0x28f790 ViewController.m:(64)> 1234

這樣發佈的時候DLog就不會有輸出了。 spa


在Objective-c開發程序的時候,有專門的日誌操做類NSLog,它將指定的輸出,輸出到(stderr),咱們能夠利用Xcode的日誌輸出窗口,那麼既然是要記錄到具體日誌文件,咱們就想輸出日誌寫入到具體的日誌文件便可。
 
代碼
一、  宏定義(下面是我在程序中經常使用到的日誌宏,用DEBUG開關管理,
也就是說只有在DEBUG模式下才讓日誌輸出 :)
 
#ifdef DEBUG 
#  define LOG(fmt, ...) do {                                            \ 
        NSString* file = [[NSString alloc] initWithFormat:@"%s", __FILE__]; \ 
        NSLog((@"%@(%d) " fmt), [file lastPathComponent], __LINE__, ##__VA_ARGS__); \ 
        [file release];                                                 \ 
    } while(0) 
#  define LOG_METHOD NSLog(@"%s", __func__) 
#  define LOG_CMETHOD NSLog(@"%@/%@", NSStringFromClass([self class]), NSStringFromSelector(_cmd)) 
#  define COUNT(p) NSLog(@"%s(%d): count = %d\n", __func__, __LINE__, [p retainCount]); 
#  define LOG_TRACE(x) do {printf x; putchar('\n'); fflush(stdout);} while (0) 
#else 
#  define LOG(...) 
#  define LOG_METHOD 
#  define LOG_CMETHOD 
#  define COUNT(p) 
#  define LOG_TRACE(x) 
#endif
 
能夠看到,除了標準的用戶定義輸出外,我還加入了許多有用的信息,
好比源程序文件位置,行號,類名,函數名等。具體的應用能夠在具體的開發過程當中添加、刪除。
 
二、  應用:
- (void)redirectNSLogToDocumentFolder{ 
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0]; 
    NSString *fileName =[NSString stringWithFormat:@"%@.log",[NSDate date]]; 
    NSString *logFilePath = [documentsDirectory stringByAppendingPathComponent:fileName]; 
    freopen([logFilePath cStringUsingEncoding:NSASCIIStringEncoding],"a+",stderr); 

 
- (void)applicationDidFinishLaunching:(UIApplication *)application { 
    // 真機測試時保存日誌 
    if ([CDeviceInfo getModelType] != SIMULATOR) { 
        [self redirectNSLogToDocumentFolder]; 

}
 
真機測試的時候,能夠利用freopen將標準錯誤輸出保存到指定的文件當中,
這樣就能夠在問題發生後分析日誌文件。
 
三、  設置DEBUG標誌是否正肯定義
 
Xcode 通常會在 debug 運行配置項裏面已經定義號了DEBUG 標誌,若是沒定義咱們就本身寫上,以個人 Xcode 4 爲例,在項目get Info中找到 PreProcessor Macros 這個屬性,對於 Debug 配置咱們給他寫上 DEBUG,而在 Release 配置中把它留空。 這樣咱們剛纔那段預處理命令就能夠根據這個標誌來判斷咱們編譯的時調試版本仍是發佈版本,從而控制 NSLog 的輸出。 (由於 Xcode 4 會把 debug/release 兩個配置項同時對比展示出來,而 3.x 版本的只能分別設置,若是你用的時xcode 3.x 開發工具, 那麼就分別對 Debug/Release 都檢查一下)。debug

相關文章
相關標籤/搜索