How to define a global variable that can be accessed anywhere in my application?

Benoît Freslon picture Benoît Freslon · May 20, 2011 · Viewed 79.7k times · Source

Possible Duplicate:
Global int variable objective c

I would like to create a global variable. I want to access to this variable anywhere.

The Java equivalent:

static var score:int = 0;

For example if I define a global variables into the Game class. How to access to this global variable?

Game.score ?

Answer

Nitish picture Nitish · May 20, 2011

If you are having multiple views in your application, and in that case you want to have a variable accessible to every view, you should always create a Model/Data class and define the variable in it. Something like this :

Objective-C :

//DataClass.h      
@interface DataClass : NSObject {    

    NSString *str;
}

@property(nonatomic,retain)NSString *str;    
+(DataClass*)getInstance;    
@end  


//DataClass.m    
@implementation DataClass    
@synthesize str;

static DataClass *instance = nil;

+(DataClass *)getInstance
{    
    @synchronized(self)    
    {    
        if(instance==nil)    
        {    
            instance= [DataClass new];    
        }    
    }    
    return instance;    
}    

Now in your view controller you need to call this method as :

DataClass *obj=[DataClass getInstance];  
obj.str= @"I am Global variable";  

This variable will be accessible to every view controller. You just have to create an instance of Data class.

Swift :

class DataClass {

    private var str: String!

    class var sharedManager: DataClass {
        struct Static {
            static let instance = DataClass()
        }
        return Static.instance
    }
}

Usage : DataClass.sharedManager.str

Using dispatch_once

class DataClass {

    private var str: String!

    class var sharedInstance: DataClass {
        struct Static {
            static var onceToken: dispatch_once_t = 0
            static var instance: DataClass? = nil
        }
        dispatch_once(&Static.onceToken) {
            Static.instance = DataClass()
        }
        return Static.instance!
    }
}  

Usage : DataClass.sharedManager.str