several ways to use global variables in the iphone development(
Method 1: Use static variables (not recommended)
Method 2: Use singleton pattern (ref link:http://nice.iteye.com/blog/855839)
Method 3: Set the global variable to Appdelegate
In the iphone development, there are several implementations for using global variables:
1. Declare and initialize global variables in appdelegate
Then insert the following code where you want to use the variable:
Get Appdelegate, in iOS, Appdelegat is designed to be a single case pattern
Appdelegate *appdelegate = [[UIApplication sharedapplication] delegate];
Appdelegate.your Variable
2. Use the extern keyword
2.1 Create a new Constants.h file (file name as needed) for storing global variables;
2.2 Write the global variable name you need in the Constants.h,
Example: NSString *url;//pointer type
int count;//non-pointer type
Note: You cannot initialize a global variable when it is defined, or an error occurs.
2.3 Introduce this file in a file that requires global variables:
#import "Constants.h"
2.4 Initialize or assign values to global variables:
extern NSString *url;
URL = [[NSString alloc] initwithformat:@ "http://www.google.com"];
pointer type; Alloc (I tried the direct URL = @ "www.google.com" seems to be able to access)
extern int count;
Count = 0;//non-pointer type
2.5 Using global variables: As with normal variables.
Method Two: iOS single example global variable writing
Interface Mysingleton:nsobject
{
⇒①nsstring *testglobal;
}
+ (Mysingleton *) Sharedsingleton;
⇒② @property (nonxxxx,retain) NSString *testglobal;
@end
@implementation Mysingleton
⇒③ @synthesize Testglobal;
+ (Mysingleton *) Sharedsingleton
{
Static Mysingleton *sharedsingleton;
@synchronized (self)
{
if (!sharedsingleton)
Sharedsingleton = [[Mysingleton alloc] init];
return Sharedsingleton;
}
}
@end
Change the place of ①, ②, ③ to what you want,
Use Example:
[Mysingleton Sharedsingleton].testglobal = @ "Test";