When writing code for a particular platform it is important to be mindful of idioms and best practices for that platform. Throughout Apple’s framework headers and open source code string constants are always declared and defined consistently.
Besides matching the existing style and expectations, there are practical reasons for declaring your string constants as Apple does.
- direct pointer comparison
- clear intent
- documentation
In a header file declare your string constant like this.
In the corresponding implementation file define the constant like this.
Now you can use pointer comparisons rather than using isEqual:
or
isEqualToString:
.
Preprocessor defines are great for many things, but are not great for
constants. Constants should be declared as const
so the intent is
clear. Preprocessors defines, by default, only display a warning if
redefined and can be trivially suppressed. In contrast, redefining a
constant is a linker error and halts compilation.
The biggest benefit is the ability to use direct pointer comparison
which is constant time rather than isEqual:
or isEqualToString:
which can be O(n) at worst.