Global Variables in Cocoa/Objective-C?

Just to be clear, the recommendation is to create immutable global variables instead of in-line string constants (hard to refactor and no compile-time checking) or #defines (no compile-time checking). Here's how you might do so...

in MyConstants.h:

extern NSString * const MyStringConstant;

in MyConstants.m:

NSString * const MyStringConstant = @"MyString";

then in any other .m file:

#import "MyConstants.h"

...
[someObject someMethodTakingAString:MyStringConstant];
...

This way, you gain compile-time checking that you haven't mis-spelled a string constant, you can check for pointer equality rather than string equality[1] in comparing your constants, and debugging is easier, since the constants have a run-time string value.

[1] In this use, you are essentially using the pointer values as the constants. It just so happens that those particular integers also point to strings that can be used in the debugger


Global variables or a singleton will accomplish the same thing here. Both can be used to turn 'key' names in Cocoa that won't throw a compiler error if it's misspelled into a compiler error. That's the main purpose. Global variables are a bit easier though seeing as it requires less typing.

Instead of doing this:

[myArray setObject:theObject forKey:MyGlobalVariableKeyName];

You'd have to do something along the lines of:

[myArray setObject:theObject 
            forKey:[[MySingletonVariableClass getInstance] myVariableKeyName];

Global variables are essentially less typing for the same effect.


Calling it a global variable is technically correct but misleading.

It is a global constant -- global in scope but constant and therefore not bad in the sense that global variables are bad.

To show how global constants are common, safe and numerous, consider these examples of global constants:

  • Every class in your program
  • Every #define
  • Every enum
  • Almost every name declared by Cocoa (excluding rare global variables like NSApp).

The only time you should worry about global constants is when their names are too generic (they may pollute the global namespace). So don't use names that are likely to conflict with anything (always use a prefix and always make the name task-specific like NSKeyValueObservingOptionNew).