Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use static string vs. #define

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.

like image 345
mahboudz Avatar asked Jan 19 '10 08:01

mahboudz


People also ask

What is a static string?

Static string is the largest selling ionizing cord in the world because it produces 20 times the ionization of any other ion cord or tinsel product! Static String® provides clean performance with no oxidation, copper contamination or scratching.

Why do we use static final?

The static keyword means the value is the same for every instance of the class. The final keyword means once the variable is assigned a value it can never be changed. The combination of static final in Java is how to create a constant value.

Why are strings static in Java?

The static keyword in Java is used to share the same variable or method of a given class. The users can apply static keywords with variables, methods, blocks, and nested classes. The static keyword belongs to the class than an instance of the class.


1 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.

like image 178
cdespinosa Avatar answered Oct 23 '22 00:10

cdespinosa