const vs static NSStrings in Objective-C

Solution 1:

static keyword in Objective-C (and C/C++) indicates the visibility of the variable. A static variable (not in a method) may only be accessed within that particular .m file. A static local variable on the other hand, gets allocated only once.

const on the other hand, indicates that the reference may not be modified and/or reassigned; and is orthogonal on how it can be created (compilers may optimize consts though).

It's worth mentioning that NSString literals get initialized and never get destroyed in the life of application. They are allocated in a read-only part of the memory.

Solution 2:

The static only changes the scope of the variable, not how it is declared or stored.

In both cases, the compiler will create a constant version of the NSString instance that is stored in the mach-o file. Thus, there is only ever one instance of either (note that you can change the behavior to cause the string to be dynamically created on load of the mach-o, but there is still just one instance).

The static just marks the aVar variable as being visible within the scope of the compilation unit -- the file -- only. Without the static, you could redeclare the string as extern NSString *aVar; in a header somewhere and have access to it from anywhere.

The const is orthogonal and, in the case of of NSString reference is pretty much entirely irrelevant.

Solution 3:

In order to resolve all possible discussions on need of static and position of const:

According to C99/GNU99 specification (which usually used for Objective-C code):

  • static

    • is storage-class specifier

    • objects of file level scope by default has external linkage

    • objects of file level scope with static specifier has internal linkage
  • const

    • is type-qualifier (is a part of type)

    • keyword applied to immediate left instance - i.e.

      • MyObj const * myVar; - unqualified pointer to const qualified object type

      • MyObj * const myVar; - const qualified pointer to unqualified object type

    • Leftmost usage - applied to the object type, not variable

      • const MyObj * myVar; - unqualified pointer to const qualified object type

THUS:

static NSString * const myVar; - constant pointer to immutable string with internal linkage.

Absence of the static keyword will make variable name global and might lead to name conflicts within the application.