How To Use Static Variables – Internal and Global

Static variable have a few variations, regardless of the usage, all static variable have one common attribute, they remain in existence for the life of the program.

Internal Static Variable

Let’s start with an internal static variable – assume you have the following code in a method:

- (void)someMethod
  static int x = 0;
  NSLog(@"x is: %d", x++);

The lifetime of the internal static variable x will be equal to the application lifetime. Thus, upon each invocation of someMethod, the value of x will be increased by 1.

Using a static variable in a manner such as this allows you locally maintain a counter or some other type value that needs to maintain its value and be used only locally within a method/function.

Global Static Variable

If you move the declaration of the static variable so it is not inside a method/function, the variable is then visible globally within the file where it is defined.

With this approach, all methods/functions in the file will have access to the variable. Again, the variable maintains it value for the duration of the application lifecycle.

Although not a common practice, there are times that a static variable can be of great value.