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
?
While they are both rooted in C, they are two completely different languages. A major difference is that Objective-C is focused on runtime-decisions for dispatching and heavily depends on its runtime library to handle inheritance and polymorphism, while in C++ the focus usually lies on static, compile time, decisions.
Objective-C and C# are very different languages both syntactically and from a runtime standpoint. Objective-C is a dynamic language and uses a message passing scheme, whereas C# is statically typed.
Objective-C is so pervasive in iOS that it's impossible to completely remove it. Apple continues to maintain libraries written in Objective-C, so we should expect Objective-C to be treated as a (mostly) first class language in iOS. At other companies, legacy code remains.
When Objective-C migration is perfect and developers beg managers for permission, Apple will say, "You should really be using Swift", and discourage Objective-C. Years later, it may be deprecated, but it never will be removed. It powers iOS, and years after deprecation OS X still runs bits of Carbon.
#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.
#if
is a preprocessor directive.
if
is a language construct.
The difference is in the way that the final program is compiled into. When you use #if
, the result of that directive is what the final program will contain on those lines. When you use the language construct, the expression that is passed to the construct will be evaluated at runtime, and not compile-time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With