Apr 12

In general try to avoid to set too many global variables, instead use local class variables instead to keep things as less complicated as possible.
But sometimes it can come in handy to set variables in your app that you can address from all your classes.

The easiest way to do this, is to use your AppDelegate class for this. You can just include your AppDelegate where needed and address the functions and variables that are in there.

First, define the variables in the AppDelegate’s .h and .m files:

#import <UIKit/UIKit.h>

@interface My_ApplicationAppDelegate : NSObject <UIApplicationDelegate, UITabBarControllerDelegate> {
    UIWindow *window;
    NSInteger *myGlobalInteger;
@property (nonatomic, assign) NSInteger *myGlobalInteger;

#import "My_ApplicationAppDelegate.h"
@implementation My_ApplicationAppDelegate
@synthesize window,myGlobalInteger;

To access these global variables from and to your AppDelegate class, first include your AppDelegate in the .m file of the class where you need it.

#import "My_ApplicationAppDelegate.h"

And then define the following in the function where you need to access the variable:

- (void)myFunction {
        My_ApplicationAppDelegate *appDelegate = (My_ApplicationAppDelegate *)[[UIApplication sharedApplication] delegate];
        appDelegate.myGlobalInteger = 1;
        NSLog(@"The integer value is %i",myGlobalInteger);

And voila, you can access the myGlobalInteger value from everywhere where you allocate the My_ApplicationAppDelegate like shown above.

Leave a Reply

preload preload preload