Question

Static NSString usage vs. inline NSString constants

In Objective-C, my understanding is that the directive @"foo" defines a constant NSString. If I use @"foo" in multiple places, the same immutable NSString object is referenced.

Why do I see the following code snippet so often (for example in UITableViewCell reuse)?

static NSString *CellId = @"CellId";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellId];
if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle:style reuseIdentifier:CellId];

Instead of just:

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CellId"];
if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle:style reuseIdentifier:@"CellId"];

I assume it is to protect me from making a typo in the identifier name that the compiler wouldn't catch. But if so, couldn't I just use

#define kCellId @"CellId"

and avoid the static NSString * bit? Or am I missing something?

 45  23127  45
1 Jan 1970

Solution

 61

It's good practice to turn literals into constants because:

  1. It helps avoid typos, like you said
  2. If you want to change the constant, you only have to change it in one place

I prefer using static NSString* const, because it's slightly safer than #define. I tend to avoid the preprocessor unless I really need it.

2009-12-21

Solution

 35

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 (i.e., "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";

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, a la...

#define SomeStupidString @"DefiningConstantsTwiceIsForIdiots"

Use #define's... they are way less annoying.. Just don't let the preprocessor-player-haters get you down.

2012-12-03