ElvK
ElvK

Reputation: 3

Access Variable From Any File

I have an objective-c/xcode project with several header and implementation files. I'd like to declare a variable that I can read and change from any file associated with the project. I tried doing extern int val = 0; in a header, but that lead to a linker error.

Would appreciate any help, thanks.

Upvotes: 0

Views: 118

Answers (2)

hotpaw2
hotpaw2

Reputation: 70703

Put the:

extern int val;

in at least one header file included by any .m or .c file where you want to use this global variable. Including an assignment here is almost always an error.

Put

int val = 0;

outside any function or method scope, in exactly one .m or .c file included in your build. No more.

If you access this variable often, and care about performance and battery life, using NSDefaults is several orders of magnitude slower than accessing a global variable. Using the app delegate for singleton model objects is also somewhat slower, and produces slightly larger apps.

Upvotes: 0

PengOne
PengOne

Reputation: 48398

For storing and accessing an int in and iOS app, I recommend using NSUserDefaults.

You can set the value from anywhere in the application by

NSUserDefaults *defaults = [NSUserDefaults  standardUserDefaults];
[defaults setInteger:anInt forKey:@"IntKey"];
[defaults synchronize];

Then you can retrieve the value from anywhere in the application by

NSUserDefaults *defaults = [NSUserDefaults  standardUserDefaults];
int a = [defaults integerForKey:@"IntKey"];

This also works great for BOOL, float, NSString and NSArray. Check out the NSUserDefaults documentation for more details and examples.

Upvotes: 1

Related Questions