デバッグ時だけログを出力させたい

iOSアプリでコンソールにログをだしっぱなしにすると申請時にNGになるとか。でも、開発時にはログを出しときたい。どーしましょと思ってたら、マクロ使えば良いんだね。だってベースはC言語なんだし。:-)

参考にさせてもらったのはこちら


書き方はこんな感じ。これを MyApp_Prefix.pch に埋めこんでおけば OK

#ifdef DEBUG
  #define DLog(fmt, ...) NSLog((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__);
#else
  #define DLog(...)
#endif


マクロ変数の意味はこんな感じ

マクロ変数 役割
__PRETTY_FUNCTION__ 関数/メソッド名(引数、戻り値付き)
__LINE__ 行番号
__VA_ARGS__ 可変長引数


使い方はこんな感じ(command line プロジェクト)

#ifdef DEBUG
#   define DLog(fmt, ...) NSLog((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__);
#else
#   define DLog(...)
#endif

#import <Foundation/Foundation.h>

int main (int argc, const char * argv[])
{
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    DLog(@"message");
    [pool drain];
    return 0;
}


実行してみるとこんな感じ

2011-08-19 09:44:25.985 NSLog1[48999:903] int main(int, const char **) [Line 12] message
Program ended with exit code: 0


ちなみに ##__VA_ARGS__の ## ってなんだろ?って思ってたら、コメントにこんな記述があった。

The '##' notation is a GNU extension to the standard C preprocessor notation which allows zero arguments in lieu of the ellipsis where the C standard requires at least one argument. – Jonathan Leffler Dec 22 '10 at 15:56

NSLog tips and tricks - stackoverflow


C言語プリプロセッサで定義された表記法の1つで ## をつけると引数がゼロでもOKになるそーな。知らなかったわ ^^;)>

おまけ

DEBUG の定義は GCC_PREPROCESSOR_DEFINITIONS で設定されてる。Xcode で見る場合、ここを見ましょ。:-)

おまけ2

MyApp_Prefix.pch に定義した DLog を使うと warning が出る。原因はなんでしょ? :-(

Implicit declaration of function 'DLog' is invalid in C99

ググってみると Xcode4.0.2 のバグって記述もあるけど、ホントのとこ、どーなんだろ?

It seems it was a bug in XCode... 4.0.2 I think. 4.2 betas work fine. – Milos

Implicit declaration of function - C99 - stackoverflow
環境
  • Mac OSX 10.6.8
  • Xcode 4.0.2