iPhone Development: Global Variables

丶灬走出姿态 提交于 2020-01-16 19:06:32

问题


I am very new to Objective-C. I need to make a global variable. I have the files abc.h, abc.m, aaa.h, aaa.m and of course, the app delegate.

I want to declare it in abc.h, use have the user assign it in abc.m and it be used in aaa.m. I want the variable to be an integer named x. I heard that I can use the App Delegate Somehow. I want the assigning variable in abc.m to be implemented in the middle of my code. Since I'm new, please make it simple!!

Thanks in Advance!


回答1:


You can use a property in your application delegate, as you can always get the app delegate instance with:

[ [ UIApplication sharedApplication ] delegate ]

So:

/* AppDelegate.h */
@interface AppDelegate: NSObject < UIApplicationDelegate >
{
    int x;
}
@property( readonly ) int x;
@end

/* AppDelegate.m */
#import "AppDelegate.h"
@implementation AppDelegate
@synthesize x;
@end

This way, you'll be able to use:

[ [ [ UIApplication sharedApplication ] delegate ] x ]

Another approach is to use a global variable, declared as extern in your abc.h file, and defined in the abc.m file.

/* abc.h */
extern int x;

/* abc.m */
int x = 0;

This way, other files will be able to access x, only by including abc.h. extern tells the compiler that the variable will be defined later (e.g. in another file), and that it will be resolved at link time.




回答2:


Instead of putting all the burden in AppDelegate I'll recommend you to create your own singleton class, and then use it anywhere you want to use. Here is the sample of creation of singleton class: http://www.71squared.com/2009/05/iphone-game-programming-tutorial-7-singleton-class/




回答3:


I'd recommend creating your own singleton class so as to avoid cluttering up the UIApplication delegate. It also makes your code neater. Subclass NSObject and add code a bit like the following:

static Formats *_formatsSingleton = nil;
+ (Formats*) shared
{
    if (_formatsSingleton == nil)
    {
        _formatsSingleton = [[Formats alloc] init];
    }
    return _formatsSingleton;
}

Add ivars and properties to this class as required. You can set default values in an init method, e.g.

- (id) init;
{
    if ((self = [super init]))
    {
        _pgGlobalIntA = 42;   // ivar for an int property called globalInt
        _pgGlobalStringB = @"hey there";   // ivar for an NSString property called globalStringB
    }
    return self;
}

And then to set and access you'd use:

 [[Formats shared] setGlobalIntA: 56];
 NSLog(@"Global string: '%@'", [[Formats shared] globalStringB]);

The class method shared creates an instance of the class if one doesn't exist already. So you don't have to worry about creating it. It'll just happen the first time you try to access or set one of your globals.



来源:https://stackoverflow.com/questions/7368820/iphone-development-global-variables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!