Search code examples
iosobjective-ccocos2d-iphoneencapsulation

How Can I Make an int Variable That I Can Read/Write To At Any Time From Anywhere In The Code


I'de like to declare an int variable in my program, so that I can change and get the value of it anywhere in the program, at any time.

I'm not sure of the syntax to fetch that value, or even how to set the value, nor do i know where I should declare it, and of course, I'm not sure if it should be an @property somewhere...

The usage is so that in my Cocos2d game I can get my Main Menu to set the figure as the TMX Tile Map level to load up in my scene. Like this...

-(id) init {if((self=[super init]))
    {
        self.tileMap = [CCTMXTiledMap tiledMapWithTMXFile:
            [NSString stringWithFormat:@"level%i.tmx", levelToLoadUp ,nil]];
    } return self;
}

I'm having difficulty finding this specific section of the encapsulation tutorials, and fell I should ask it here since I feel its a fairly simple question to answer.. "How do I make a program wide variable"

Thanks


Solution

  • This is called a global variable. It is usually not recommended which is probably why you are having a hard time finding anything on it.

    Pick wherever you want to add it (declared).

    //in any file outside of the main code (preferably right after the imports)
    int gSomeGlobal = 5;
    

    To access in another part, just put the extern keyword in front.

     //Access from any file
     extern int gSomeGlobal;
     int myValue = gSomeGlobal;
    
     NSLog(@"%i",myValue);  // prints 5
    

    If you want to do this the right way, look into the SINGLETON pattern. In essence, you want to localize all your variables into one file to make it more clear and easy to read. http://www.galloway.me.uk/tutorials/singleton-classes/