开发者

iPhone: Suppress NSLog in production?

I got a bunch of NSLog statements in my code. Is there anyway I can suppress them from executing in production, but execute when I'm developing? I want to not comment them out, and them put 开发者_开发技巧them back in when developing, as it's a hassle.


DEBUG is a macro that is only defined (xcode default) when you are doing a debug/development build of your project. This will cause any code between the #ifdef DEBUG and #endif lines to not be included when doing a release build but they will be compiled and included with a debug/dev/test build.

Example:

#ifdef DEBUG
    NSLog(@"Hello World!");
#endif

This is what I use in my Project-Prefix.pch file (called with DEBUGLOG(@"abc %@", someStr);):

#ifdef DEBUG
    extern void DBGQuietLog(NSString *format, ...);
    #define DEBUGLOG(fmt, ...) DBGQuietLog((@"[Line: %d] %s: " fmt), __LINE__, __FUNCTION__, ##__VA_ARGS__);
#else
    #define DEBUGLOG(fmt, ...)
#endif

#ifdef DEBUG
    void DBGQuietLog(NSString *format, ...) {
        if (format == nil) {
            printf("nil\n");
            return;
        }
        va_list argList;
        va_start(argList, format);
        NSString *s = [[NSString alloc] initWithFormat:format arguments:argList];
        printf("%s\n", [[s stringByReplacingOccurrencesOfString:@"%%" withString:@"%%%%"] UTF8String]);
        [s release];
        va_end(argList);
    }
#endif

This prints console lines (only when debugging) with line number, class name, and method name like so:

[Line: 36] -[iPhoneAppDelegate application:didFinishLaunchingWithOptions:]: Hello World!


You could make a proxy and define it as a preprocessor macro:

#ifdef DEBUG
#define MyLog(str, ...) NSLog(str, ##__VA_ARGS__)
#else
#define MyLog(str, ...) 
#endif

Then you'd use MyLog() instead of NSLog() in your code and when not compiling in debug mode the NSLog would be replaced with a no-op.


As an extension to CajunLuke's answer, I can only advise you to use this: http://kdl.nobugware.com/post/2009/03/11/better-nslog/


Wrap them with a macro. It's unfortunate that Apple doesn't do this already, with a "canned" solution, but many folks do it, and there are a number of examples on the web.

Something like:

#ifdef DEBUG_MODE
#define DebugLog( s, ... ) NSLog(@"<%@:(%d)> %@", [NSString stringWithUTF8String __PRETTY_FUNCTION__], __LINE__, [NSString stringWithFormat:(s), ##__VA_ARGS__] )
#else
#define DebugLog( s, ... )
#endif

(Hopefully got that right -- copied by hand from another screen)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜