Reputation:
can anyone tell how to declare and change global variables in objective c
Upvotes: 0
Views: 2549
Reputation: 109
Global Variable for Complete iPhone Project
For Declare/Define/Use a global variable follow these easy steps:-
Create a NSObject File with named "GlobalVars.h and .m" or as u wish
Declare your global variable in GlobalVars.h file after #import and before @implementation like-
extern NSString *Var_name;
initialize it in GlobalVars.m file after #import and before @implementation like-
NSString *Var_name = @"";
Define its property in AppDelegate.h File
@property (nonatomic, retain) NSString *Var_name;
synthesize it in AppDelegate.m File like-
@synthesize Var_name;
Now where you want to use this variable (in .m file) just import/inclue GlobalVars.h file in that all .h files, and you can access or can changes easily this variable.
Carefully follow these Steps and it'll work Surely.
Upvotes: 2
Reputation: 1366
Single source file:
int myGlobal;
Header file:
extern int myGlobal;
Any file including the header:
myGlobal = 10;
Upvotes: 1
Reputation: 29009
On a related note; global variables are (very) generally speaking considered a Bad Thing™. In Obj-C the more common approach is making them a property on a singleton object, ensuring at least some encapsulation is taking place.
In an AppKit/UIKit application; a global variable might more properly be a property on your application delegate; another, somewhat more involved, option is making a singleton class for encapsulating the variable and related methods.
Upvotes: 2
Reputation: 22493
Just the same way that you would in C. Are you having any particular problem?
Upvotes: 3