13

I want to disable NSLog() across all instances in an app. I found some code that does that:

#ifndef DEBUG
#define NSLog //
#endif

But adding this code to each file isn't good idea. How can I make it easier?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Timur Bernikovich
  • 5,660
  • 4
  • 45
  • 58

5 Answers5

11

Xcode has a precompiled header file ({project-name}-Prefix.pch in the Supporting Files group by default) that is a great place to put code that will be used across every file in the project. For going a step further and improving the log message itself, see Is it true that one should not use NSLog() on production code?.

Community
  • 1
  • 1
jszumski
  • 7,430
  • 11
  • 40
  • 53
6

Add the following lines to your constants file:

#define DEBUGGING NO    //or YES
#define NSLog if(DEBUGGING)NSLog

The two following sentences give the same results

#define NSLog

and

#define NSLog //

because all text that begin with // are deleted in a precompiling phase ("//" included)

Miguel Gallego
  • 427
  • 4
  • 7
  • your // suggestion is dangerous because you can spread NSLog over multiple lines. your if statement looks flaky too... you could use a scoped if and parameters for the NSLog macro to make it better... – jheriko Jun 12 '15 at 16:01
2

What I do is put this in the precompiled header file (YourAppName.pch):

#define MyLog if(0); else NSLog

Then I change all NSLog to MyLog everywhere else in the app. It works as if it were NSLog. But when you want to disable NSLog, go back to the .pch file and change the 0 to 1 and presto, all logging stops.

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • 2
    This is dangerous because it changes the binding of any subsequent `else`. I.e. `if (someCondition) MyLog(blah); else doSomething();` doesn't mean what it appears to. – Ken Thomases Apr 14 '13 at 17:58
  • @KenThomases Don't look at me, I got it from Jens Alfke! I haven't run into any issues like that yet, but I'm sure your warning is a good one. – matt Apr 14 '13 at 18:15
2

This will also take care of the warnings that arise when using

#define NSLog //

The code:

#ifndef DEBUG
  #define NSLog(...)
#endif
Eyeball
  • 3,267
  • 2
  • 26
  • 50
0

Just add the following lines when you do'"t need NSLOG to your constants file

#define NSLog                       //

and comment it when you need it.

Rajeev Barnwal
  • 1,349
  • 11
  • 14