When to use static string vs. #define

Viewed 33418

I am a little confused as to when it's best to use:

static NSString *AppQuitGracefullyKey = @"AppQuitGracefully";

instead of

#define AppQuitGracefullyKey    @"AppQuitGracefully"

I've seen questions like this for C or C++, and I think what's different here is that this is specifically for Objective C, utilizing an object, and on a device like the iPhone, there may be stack, code space or memory issues that I don't yet grasp.

One usage would be:

appQuitGracefully =  [[NSUserDefaults standardUserDefaults] integerForKey: AppQuitGracefullyKey];

Or it is just a matter of style?

Thanks.

6 Answers

If you use a static, the compiler will embed exactly one copy of the string in your binary and just pass pointers to that string around, resulting in more compact binaries. If you use a #define, there will be a separate copy of the string stored in the source on each use. Constant string coalescing will handle many of the dups but you're making the linker work harder for no reason.

See "static const" vs "#define" vs "enum". The main advantage of static is type safety.

Other than that, the #define approach introduces a flexibility of inline string concatenation which cannot be done with static variables, e.g.

#define ROOT_PATH @"/System/Library/Frameworks"
[[NSBundle bundleWithPath:ROOT_PATH@"/UIKit.framework"] load];

but this is probably not a good style :).

I use static when I need to export NSString symbols from a library or a framework. I use #define when I need a string in many places that I can change easily. Anyway, the compiler and the linker will take care of optimizations.

Related