static NSString usage vs. inline NSString constants
It's good practice to turn literals into constants because:
- It helps avoid typos, like you said
- If you want to change the constant, you only have to change it in one place
I prefer using static const NSString*
static NSString* const
because it's slightly safer than #define
. I tend to avoid the preprocessor unless I really need it.
I love all the answers here without a simple example of how to correctly declare one... so...
If you want the constant to be externally visible (ie. "global").... declare it as such in a header...
extern NSString *const MyTypoProneString;
and define it in a .m
file, OUTSIDE any @implementation
like...
NSString * const MyTypoProneString = @"iDoNtKnOwHoW2tYpE";
That said... if you simply want a static const
that IS LOCAL to your class' implementation (or even a certain method!)... simply declare the string INSIDE the implementation (or method) as...
static NSString *MavisBeacon = @"She's a freakin' idiot";
EDIT Although I do show how to do this... I have yet to be convinced that this style is in any way better than the ridiculously shorter, simpler, and less repetitive SINGLE declaration, á la..
#define SomeStupidString @"DefiningConstantsTwiceIsForIdiots"
Use #define
's... they are way less annoying.. Just don't let the preprocessor-player-haters get you down.
You should make the static variable const
.
One difference between static variable and a macro is that macros don't play well with debuggers. Macros also aren't type-safe.
Much of the static-var-vs-macro advice for C and C++ applies to Obj-C.