Get Updates By E-mail 

Subscriber Counter
Article Written By:
Johann Dowa

Global Variables in iPhone Objective-C

If you studied any programming in school you were probably told to never use global variables because ultimately it can cause you end up with a messy slob of code that is difficult to maintain, and this holds true in iPhone Objective-C.

While that is correct, the truth of the matter is there are many situations when you want to have a global variable, as often there are variables that don’t really belong to any objects, and you want to change them from many locations within your application.  You could of course place variables in your AppDelegate and access them through there, but this is not a good solution and can turn things into a great big mess which is the reason why many college professors forbid the use of global variables in all languages (not simply because they may have never actually coded anything).  The solution to this is to create a class using the Singleton design pattern.  For example:

@interface VariableStore : NSObject
{
    // Place any "global" variables here
}
// message from which our instance is obtained
+ (VariableStore *)sharedInstance;
@end

@implementation VariableStore
+ (VariableStore *)sharedInstance
{
    // the instance of this class is stored here
    static VariableStore *myInstance = nil;
 
    // check to see if an instance already exists
    if (nil == myInstance) {
        myInstance  = [[[self class] alloc] init];
        // initialize variables here
    }
    // return the instance of this class
    return myInstance;
}
@end

Whenever you need to access a variable assuming you have a getter defined as the variable name simply use:

[[VariableStore sharedInstance] variableName]

If the variable is a primitive, and a global constant then there is really no need to use a singleton as above you can use a preprocessor #define statement. For example:

#define VARIABLE value

Now when you need to share a variable between many objects this should make for much simpler, and cleaner code.

If you’re transitioning to Objective-C from C/C++/Java you might want to check out my Objective-C Cheat Sheet.

Submit A Resource

Have you created a useful tutorial, library or tool for iOS development that you would like to get in front of our 300,000+ monthly page views from iOS developers?

You can submit the url here.

The resources we feel will appeal to our readers the most will be posted on the front page.

Comments