73

I don't quite understand static variables when defined in the implementation of an interface. In methods I do understand how they differ from local variables, but not when defined directly in an implementation.

Look at these examples. What difference do these two make practically?

#include "MyClass.h"

@implementation MyClass
int myInt;
...
@end

And:

#include "MyClass.h"

@implementation MyClass
static int myInt;
...
@end

myInt is in both cases visible to all the methods, and if I interpreted a test I ran correctly, myInt will in both cases be the same variable for different instances of the class.

Bakuriu
  • 98,325
  • 22
  • 197
  • 231
quano
  • 18,812
  • 25
  • 97
  • 108

4 Answers4

93

Unfortunately, it has different effects depending on where you use it.

Static Functions:
By default, all functions have a global scope. The static specifier lets you limit the function’s scope to the current file.

Static Local Variables:
When you use the static modifier on a local variable, the function “remembers” its value across invocations. For example, the currentCount variable in the following snippet never gets reset, so instead of storing the count in a variable inside of main(), we can let countByTwo() do the recording for us.

// main.m
#import <Foundation/Foundation.h>

int countByTwo() {
    static int currentCount = 0;
    currentCount += 2;
    return currentCount;
}

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        NSLog(@"%d", countByTwo());    // 2
        NSLog(@"%d", countByTwo());    // 4
        NSLog(@"%d", countByTwo());    // 6
    }
    return 0;
}

This use of the static keyword does not affect the scope of local variables.
Read more about the static keyword.

Michael Kohne
  • 11,888
  • 3
  • 47
  • 79
appsunited
  • 1,667
  • 16
  • 22
  • 8
    The static keyword will enforce its line to be executed ONLY once for the entire application runtime--regardless of the number of invocations! – mfaani Apr 08 '16 at 12:12
  • Where in memory is the static variable "currentCount" stored? It can't be in countByTwo's frame because that frame is deallocated when the function ends. So where is it stored? – Enrique Feb 15 '17 at 14:40
  • @Enrique in the same data/bss areas that the other "global" variables live, it's just the scope that is local – BjornW Oct 07 '18 at 10:01
72

The 'static' keyword in that context is the same as it would be in plain C: it limits the scope of myInt to the current file.

smorgan
  • 20,228
  • 3
  • 47
  • 55
  • 12
    Also, defining a non-local variable inside @implementation is no different from defining it outside. – sigjuice Jul 06 '09 at 18:22
  • But does this really make any difference for definitions in implementation files? They're not included anyways. – quano Feb 28 '10 at 07:26
  • 9
    Assume you declared int Varibale; in two different implementation files. You will get errors at build time, because of duplicate symbols. – Denis Mikhaylov Apr 25 '12 at 15:04
  • 1
    Does this mean that it acts as the "private" access modifier? – glesage Oct 17 '13 at 23:22
  • 1
    No. The 'private' keyword in C++ just adds compiler-enforced restrictions on who can access a variable or method. 'static' scopes it to the just the file it's in, which is very different. – smorgan Oct 20 '13 at 04:35
  • I would replace the words "the current file" with "the compilation unit". `static`s can be `#import`ed into multiple files, but I should mention that doing so is probably (always?) a bad idea, and a misuse of `static`. – Tom Dalling Aug 27 '14 at 02:18
  • My guess is that many people who don't know what static is probably also don't know what a compilation unit is, so I simplified slightly. – smorgan Aug 30 '14 at 14:05
23

"In both C and Objective-C, a static variable is a variable that is allocated for the entire lifetime of a program. This is in contrast to automatic variables, whose lifetime exists during a single function call; and dynamically-allocated variables like objects, which can be released from memory when no longer used. More simply put, a static variable's value is maintained throughout all function/method calls. When declared outside of a function, a static variable is visible to everything within the file in which it is declared; when declared inside a function or method, it is visible only within that function or method, but the value is retained between calls."

Check out the complete explanation here:

https://stackoverflow.com/a/4965145/951349

Community
  • 1
  • 1
SmileBot
  • 19,393
  • 7
  • 65
  • 62
18

From Apple's "The Objective-C Programming Language": "Declaring a variable static limits its scope to just the class -- and to just the part of the class that's implemented in the file. (Thus unlike instance variables, static variables cannot be inherited by, or directly manipulated by, subclasses)."

c roald
  • 1,984
  • 1
  • 20
  • 30