19

for my App I'd like to have a debug view that I want to have only in debug-builds and not in release builds. I don't want to change my code though. Thats why i am wondering if I can check some compiler flag if this is a release build and exclude some code that i only want to have for debug builds.

Suragch
  • 484,302
  • 314
  • 1,365
  • 1,393
Jakob
  • 1,126
  • 3
  • 16
  • 38

3 Answers3

33

In your projects build settings, look for the preprocessor defines section, in there you can define a variable in your debug build only, such as DEBUG=1, and then use this in your code:

#if DEBUG
    NSLog(@"This will only print in debug!");
#endif

Just make sure in your release configuration, that same define is set to 0 in the same location in your build settings

Dan F
  • 17,654
  • 5
  • 72
  • 110
  • 1
    #ifdef is another option, but i prefer to use #if instead – Dan F Jan 31 '12 at 14:53
  • 2
    As I said in my comment before, I prefer to use `#if` rather than `#ifdef`. It is entirely up to the programmer which to use, and each has their advantages and disadvantages. My preference is to use the method where each flag is always defined, but as a 0 or a 1 to indicate the status of that flag, rather than trying to figure out if that flag is defined at all in the project – Dan F Apr 10 '14 at 12:21
  • 2
    #ifdef will be considered true, even if DEBUG=0 is set in the preprocessor, for that reason I consider it to be dangerous to use #ifdef – JConway Aug 07 '15 at 14:49
29

Check your projects build settings for debug to ensure that 'DEBUG' is being set - Apple gives you this for free - do this by selecting the project and clicking on the build settings tab. Search for 'DEBUG' and look to see if indeed DEBUG is being set.

Build Settings tab of my project settings

then conditionally code for DEBUG in your source files

#ifdef DEBUG

// Something to log your data here or even add a whole subview to see it on the device

#else

// 

#endif
Damo
  • 12,840
  • 3
  • 51
  • 62
  • 2
    but what if you submit the app to apple and you forget to set to DEBUG = 0 – meda Aug 14 '15 at 16:48
  • Not a problem because, as you can see in the screenshot above, in the **Release** Build Configuration, there is no definition for DEBUG; that is, there is no *DEBUG=1*, as there is for the **Debug** and *TestFlight** Build Configurations. – Jerry Krinock Apr 04 '21 at 21:41
0

In addition to the build setting explained by Damo, there is an equivalent Build Setting which I have seen used and also works. In Other C Flags (OTHER_CFLAGS), add -DDEBUG to the Debug configuration.

Jerry Krinock
  • 4,860
  • 33
  • 39