I want store a number as a global variable. What syntax do I use, and how can other parts of my application access that variable?
int gMoveNumber = 0; at the beginning of your program—outside any method, class definition, or function—its value can be referenced from anywhere in that module. In such a case, we say that gMoveNumber is defined as a global variable.
The variables that are declared outside the given function are known as global variables. These do not stay limited to a specific function- which means that one can use any given function to not only access but also modify the global variables.
The C compiler recognizes a variable as global, as opposed to local, because its declaration is located outside the scope of any of the functions making up the program. Of course, a global variable can only be used in an executable statement after it has been declared.
You probably want to use NSUserDefaults for this :
From anywhere in your code, you can set a value for a key :
int userAge = 21; // Just an example
NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
if (standardUserDefaults) {
[standardUserDefaults setObject:[NSNumber numberWithInt:userAge] forKey:@"age"];
[standardUserDefaults synchronize];
}
And get it back from any other place :
NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
NSNumber *age = nil;
if (standardUserDefaults)
age = [standardUserDefaults objectForKey:@"age"];
userAge = [age intValue]
You can also set an initial value :
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSDictionary *appDefaults = [NSDictionary
dictionaryWithObject:[NSNumber numberWithInt:13] forKey:@"age"];
[defaults registerDefaults:appDefaults];
Also, if you have complex data, you may want to create a wrapper class with setters and getters.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With