johnbakers johnbakers - 2 months ago 5
Objective-C Question

Objective C "#if" syntax

I'm a little confused by the "pound if" or

#if
syntax I see when I look at some classes.

For example:

#if someConstant == someNumber
do something
#elif
etc


versus:

if (someConstant == someNumber)
do something
else if {
do more stuff
}


what's the difference, and why use
#if
?

Answer

#if etc are preprocessor directives. This means that they are dealt with before compiling and not at runtime. This can be useful, for example, in defining debugging behaviour that only compiles when you build for debug and not release:

#if DEBUG
    #define ISRelease(x) [x release]
#else
    #define ISRelease(x) [x release], x = nil
#endif

(Code courtesy of Jeff LaMarche's blog.)

This way you don't need to go through your entire application's code just before you submit your app and remove a load of debugging code. This is just one small example of the use of these directives.