IPhone Development: Global Variables

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

I want to declare it in abc.h, use the user to assign it to abc.m and it will be used in aaa.m. I want the variable to be an integer named x. I heard that somehow I can use the application delegate. I want the assignment variable in abc.m to be implemented in the middle of my code. Since I'm new, please make it simple!

Thanks at Advance!

0
source share
3 answers

You can use the property in the application deletion, since you can always get an instance of application delegation using

[ [ 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 can 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; 

That way, other files will be able to access x only by enabling abc.h. extern tells the compiler that the variable will be defined later (for example, in another file) and that it will be resolved during communication.

+4
source

Instead of putting the whole load into AppDelegate, I recommend that you create your own singleton class and then use it anywhere you want to use it. Here is an example of creating a singleton class: http://www.71squared.com/2009/05/iphone-game-programming-tutorial-7-singleton-class/

+1
source

I would recommend creating your own singleton class so as not to clutter up the UIApplication delegate. It also makes your code tidier. Subclass NSObject and add code similar to 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 needed. You can set default values ​​in the init method, for example.

 - (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; } 

Then for installation and access you will use:

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

The shared class method creates an instance of the class if it does not already exist. Therefore, you do not need to worry about creating it. This will only happen the first time you try to access or set one of your global characters.

0
source

Source: https://habr.com/ru/post/920828/


All Articles