How to define a global variable that can be accessed anywhere in my application? [duplicate]
Asked Answered
O

3

33

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 ?
Odorous answered 19/5, 2011 at 23:29 Comment(1)
The answer on the following link explains clearly https://mcmap.net/q/452269/-global-int-variable-objective-cFreely
H
98

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

Hurwit answered 20/5, 2011 at 4:36 Comment(8)
Should that line return instance; be inside the @synchronized block?Farro
how would you get these variables in an NSManagedObject subclass where you can't edit the init method and it has no viewDidLoad to put it in?Ebarta
dispatch_once() is most prefered for singleton..see the discussion at https://mcmap.net/q/452269/-global-int-variable-objective-cFreely
Wondereful. Workable, sweet and useful code!:)Laxity
Could this be considered as Singleton Pattern ?Branny
I had problem with that .when i close application.this variable data become nil..any solution ???Badderlocks
Thanks Alot!, Btw, you have to use #import "DataClass.h" wherever you need to access the global variable.Trin
Does this work for UIImages? I tried doing exactly what was posted for the NSString but I could not figure out how to get it to work with an imageFurnace
G
20

Objective-C does not have support for "class variables" directly. Instead, you can create a variable which is valid for the scope of the class's file and access it using class methods.

// outside the implementation
static int score = 0; // static means it is only accessible from the current file

@implementation Game

+ (int)score {
    return score;
}
+ (void)setScore:(int)newScore {
    score = newScore;
}
Gypsy answered 19/5, 2011 at 23:36 Comment(3)
Thank you this helped me getting rid of the warning no static getter method named sharedInstance found return type default to idDecumbent
Simple and yet powerfulIdioblast
You made my weekend :)Kirwin
H
7

The preferred way to implement global variables in an iOS project (though these aren't true global variables), is to create a property in the application delegate, then just access that property from each of your classes.


EDIT: Re-reading your question, it looks like I misinterpreted your question, and ughoavgfhw's answer is probably what you're looking for. He's correct, there is no such thing as a class variable in Objective-C, so you have to create a regular C static variable, then create class methods (denoted by the + rather than a -) for setting and getting.

Though generally, when I need "global" variables in an app, I create singleton classes to house them and their related methods (so the app delegate doesn't overflow with unrelated properties), or if it's a smaller project I just use the application delegate (which is a also a singleton class) rather than separate singletons. Though there's nothing wrong with the static variable plus class setter/getter approach if that works better for your needs.

Hermie answered 19/5, 2011 at 23:37 Comment(4)
How does one access that property from other classes?Antung
You can always get a reference to the app delegate like this: (YourAppDelegateClass *)[UIApplication sharedApplication].delegate. I put a #define macro in the app delegate header or use a class method so that I can access it in a cleaner way, but you don't have to.Hermie
Also, if you find yourself putting a lot of stuff in the app delegate, one, you should probably rethink your approach, but if it really is needed, you may want to consider creating a separate singleton class for this, or a regular class with a reference in your app delegate.Hermie
Thanks @einsteinx2! Yes exactly! I'm realizing now that I should have a model class in this app, but given that this is (hopefully) the last workaround I'll save that lesson for the next app.Antung

© 2022 - 2024 — McMap. All rights reserved.