0

I'm creating a word game and I need to assign coins to a user:

firstly I've read over and over on subjects "Global variables" Unfortunately i'm not able to successfully do them.

I need to make 3 bool global variable such as btn1Pressed,btn2Pressed,btn3Pressed. & how to make the word "coins" global of type int as well? How is this done?

@interface MainView : 
Jeff Loughlin
  • 4,134
  • 2
  • 30
  • 47
JohnGray
  • 33
  • 8
  • possible duplicate of [declaring global variables in iPhone project](http://stackoverflow.com/questions/1249131/declaring-global-variables-in-iphone-project) – BytesGuy Apr 05 '14 at 09:59

4 Answers4

0

Using the keyword "extern" you can make variables global.

extern int coins = 9001; //over nine thousand!
Honor
  • 63
  • 2
  • 9
  • Adding an initializer to a variable with an extern definition leads to a compiler warning (or error for strict compilations). If one is going to use a global for this, it's better to define `extern int coins;` in a common header and `int coins = 9001;` in a source file. – mah Mar 25 '14 at 14:16
0

If you mean "globals" as in "accessible everywhere in your app", you can use singletons:

http://www.galloway.me.uk/tutorials/singleton-classes/

This way you can group all such global variables in one global object.

Marius Waldal
  • 9,537
  • 4
  • 30
  • 44
0

To declare global variables, you need to declare them outside of any class definition. If I have a lot of global variables, I usually put them in their own source file and call it globals.m to help keep things organized. If I only have one or two, I just declare them in the App delegate (after the #includes but before the @implementation).

int coins;
BOOL btn1Pressed;
BOOL btn2Pressed;
BOOL btn3Pressed;
// etc

Then you declare them in a common header (I use globals.h) as extern. Declare them outside of any class definition:

extern int coins;
extern BOOL btn1Pressed;
extern BOOL btn2Pressed;
extern BOOL btn3Pressed;
...

That tells the compiler that "this variable is declared elsewhere", so it knows to resolve it at link time. Include that header in any source module that needs access to those variables.

Jeff Loughlin
  • 4,134
  • 2
  • 30
  • 47
0

Using Singleton pattern is the ideal way to do it.

Create your properties in YourAppdelegate.h file for your bools btn1Pressed,btn2Pressed,btn3Pressed.Further synthesize them in YourAppdelegate.m file.

Now if you want to access or change these values in any other classes

// Accessing btn1Value
   BOOL checkTheValueOFButton1 =   [(YourAppDelegate *)[UIApplication sharedApplication]btn1Pressed];

If you want to change the value

 [(YourAppDelegate *)[UIApplication sharedApplication]setbtn1Pressed:NO];
AppleDelegate
  • 4,269
  • 1
  • 20
  • 27