I would like to create a global variable (basically a flag var) which can be modified and accessed by any class in Objective C? Any examples are appreciated.
-
6You didn't even think about googling for this, did you? – PengOne Mar 16 '12 at 16:15
-
Add a property to your application delegate. – Jeremy Mar 16 '12 at 16:16
-
possible duplicate of [Global variables in Objective-C](http://stackoverflow.com/questions/1113980/global-variables-in-objective-c) as well as http://stackoverflow.com/questions/5098990/in-objective-c-how-do-you-declare-use-a-global-variable, http://stackoverflow.com/questions/7081245/global-variables-in-xcode, and http://stackoverflow.com/questions/3601341/iphone-global-variable – jscs Mar 16 '12 at 16:38
4 Answers
Singleton pattern.
http://www.galloway.me.uk/tutorials/singleton-classes/
Always reference the object through the "sharedManager" message, that will create a new object or give you the existing one.

- 34,792
- 12
- 100
- 110

- 486
- 3
- 9
Objective C is a strict superset of ANSI C, so the steps used to create and use a plain C global variable can be used in Objective C.
In exactly one .m file, outside of any class interface, method or subroutine scope, declare or instantiate your global variable (and initialize it if you don't want it to start with a garbage value):
BOOL myGlobalFlag = NO;
To make these globals easy to find (you may need to find them, since the use of global variables is thought to be at a higher risk of being involved in certain types of bugs), put them at the top of the file, just after any required includes. Or put all your globals in one easy to find central file, such as the App Delegate, the file containing main(), or a file only containing all the globals, such as my_apps_globals.c included in your project.
In at least one .h file belonging to any class, .m, or .c file where you want to access this variable, and outside of any class interface or struct definition, declare this variable as externally accessible:
extern BOOL myGlobalFlag;
Then use the variable inside any method or subroutine, anywhere in your app, that includes any of the above header files.
-(void)dummyMethod {
if (myGlobalFlag) NSLOG(@"the Flag is set!!!");
}

- 70,107
- 14
- 90
- 153
Remember that Objective-C has good old "C" running under the covers. So you can create a global variable in Objective-C just like in C.

- 1,893
- 13
- 14
Check this. At your appname.pch file import some class, say application delegate as it is easy to access from application singleton. Add a scrip there like
#define MY_APP_DELEGATE (((MYAppDelegate *)[UIApplication sharedApplication].delegate))
and from any class use the delegate variables in this way:
int val1 = MY_APP_DELEGATE.myvar;
MY_APP_DELEGATE.myvar = 1;

- 8,904
- 2
- 39
- 74