简体   繁体   中英

Objective-C: Removing NSLog calls from 'Distribution'/production builds?

Update:

More info on this here:

Is it true that one should not use NSLog() on production code?

~~~~~~~~~~~~~~~~~~~~~~~~

Situation

I have some pretty beafy NSLog calls that I use for debugging the more complex parts of my application. However, I just recently learned that these affect runtime performance!

Goal

I would like to remove my NSLog calls during any run where I am not actually performing Product > Run (aka command-R) from within Xcode - ESPECIALLY in situations when this thing is deployed on the App Store, but also when I am running the app when disconnected from Xcode (ie just tapping the icon while walking down the street).

Proposed Solution?

Assuming I've created a Preprocessor Macro of VIEW_DEBUG, would the following implementation effectively remove NSLog calls from executing in the cases I've described above?

    <bunch of code>

#ifdef VIEW_DEBUG
    NSLog(@"really complex logs entries");
#endif

    <even more code>

This is a difficult one for me to 'test', so I figured I would appeal to more experienced minds. :)

Xcode Settings (for reference)

xcode设置

A common solution is to place the following code in your Prefix file (or you may create a dedicated class and #include it as needed):

#ifdef DEBUG    
#define DebugLog(...) NSLog(__VA_ARGS__)
#else
#define DebugLog(...) while(0)
#endif

Xcode already defines DEBUG for you when performing a debug build (as shown in your screenshot). VA_ARGS is a way of creating variadic macros that was introduced in C99. the do/while ensures that DebugLog has the same net syntactic effect even when it doesn't do anything — don't worry about the pointless loop, the optimiser will remove it for you.

Then you can just use DebugLog exactly as you'd use NSLog . This will do exactly what you propose with VIEW_DEBUG but without you having to copy and paste the #ifdef condition a thousand times over.

I always use DLog in my code, it works great.

// DLog is almost a drop-in replacement for NSLog
// DLog();
// DLog(@"here");
// DLog(@"value: %d", x);
// Unfortunately this doesn't work DLog(aStringVariable); you have to do this instead DLog(@"%@", aStringVariable);
#ifdef DEBUG
#   define DLog(fmt, ...) NSLog((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__);
#else
#   define DLog(...)
#endif

// ALog always displays output regardless of the DEBUG setting
#define ALog(fmt, ...) NSLog((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__);

More info: The Evolution of a Replacement for NSLog

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM