views:

313

answers:

2

I'm still not sure I totally get how this particular case should work out. So if I want to declare an array of NSStrings that won't change, is this correct?

static NSString * const strings[] = {@"String 1", @"String 2", ...};

Is the static necessary? (what does it do?) Am I missing an extra const somewhere? There's just too many places for it to go! Gah! Am I doing it wrong, or am I just paranoid?

+6  A: 

What you have:

static NSString * const strings[] = {@"String 1", @"String 2", ...};

Is an array of immutable pointers.

You might want:

static NSString const *strings[] = {@"String 1", @"String 2", ...};

An array of pointers to immutable NSString objects.

Or

static NSString const * const strings[] = {@"String 1", @"String 2", ...};

An array of immutable pointers to immutable NSString objects.

The "Clockwise-Spiral Rule" is the technique I use to interpret C declarations.

The static keyword means that the array's 'storage duration' is for the entire life of the program. If the declaration is in a function, then the array doesn't go away when the function returns (though the scope will still be only for that function). If the declaration is at file scope, the static keyword will make the name of the array visible only within that compilation unit (ie., source file). Another source file could not access the array through an extern declaration.

Michael Burr
Perhaps better worded as "An immutable array of pointers", "An array of immutable pointers", "An array of pointers to immutable objects", or whichever fits best.
Tordek
@Tordek - thanks for the improvement suggestion.
Michael Burr
+1 for the Clockwise-Spiral Rule
BobbyShaftoe
Since NSStrings are immutable objects, do I actually need the extra const?
Ed Marty
+1  A: 

You read C declarations from the inside out, first moving right to highly bound operators like [] and then moving left. So, you have: strings, an array, of constant, pointers, to NSString, that is static.

That's perfectly reasonable but not what you said you wanted.

To create pointers to constant strings you will need the const on the other side of the *, so you will have strings, an array, of pointers, to constant, NSString, which are static.

You can put const in both places, if you want.

Using static storage class is a bit like defining a class variable. It is the same as static in C99, a module-level lexical scope.

DigitalRoss
Objective-C doesn't have class variables. We can get the same effect as a class variable with static storage defined in the .m file, but please don't gloss over the difference.
NSResponder