Search code examples
objective-cnsstring

static NSStrings in Objective-C


I frequently see a code snippet like this in class instance methods:

static NSString *myString = @"This is a string.";

I can't seem to figure out why this works. Is this simply the objc equivalent of a #define that's limited to the method's scope? I (think) I understand the static nature of the variable, but more specifically about NSStrings, why isn't it being alloc'd, init'd?

Thanks~


Solution

  • Just stumbled upon the very same static NSString declaration. I wondered how exactly this static magic works, so I read up a bit. I'm only gonna address the static part of your question.

    According to K&R every variable in C has two basic attributes: type (e.g. float) and storage class (auto, register, static, extern, typedef).

    The static storage class has two different effects depending on whether it's used:

    • inside of a block of code (e.g. inside of a function),
    • outside of all blocks (at the same level as a function).

    A variable inside a block that doesn't have it's storage class declared is by default considered to be auto (i.e. it's local). It will get deleted as soon as the block exits. When you declare an automatic variable to be static it will keep it's value upon exit. That value will still be there when the block of code gets invoked again.

    Global variables (declared at the same level as a function) are always static. Explicitly declaring a global variable (or a function) to be static limits its scope to just the single source code file. It won't be accessible from and it won't conflict with other source files. This is called internal linkage.

    If you'd like to find out more then read up on internal and external linkage in C.