开发者

Access Variable From Any File

I have an objective-c/xcode project with several header and implementation开发者_如何学Python 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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜