const vs static NSStrings in Objective-C

后端 未结 3 1736
情歌与酒
情歌与酒 2020-12-07 16:41

These lines are both in the implementation file above the @implementation declaration.

NSString * const aVar = @\"aVarStringValue\";

static NSS         


        
3条回答
  •  生来不讨喜
    2020-12-07 17:13

    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.

提交回复
热议问题