Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global variable in Objective-C program

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?

like image 863
Shawn Avatar asked Aug 16 '11 16:08

Shawn


People also ask

How do you declare a global variable in Objective C?

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.

What is global variable in C with example?

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.

Can you declare global variables in C?

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.


1 Answers

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.

like image 52
Julien Avatar answered Oct 28 '22 14:10

Julien