What will be best approach to declare global variables in iphone sdk?
I am new in iphone, i just develop two little app, and in these app when i required project level global variables i used to declare in app delegate, but i read in somewhere that this is not best approach, so can someone tell me what will be best approach to declare proj开发者_如何学运维ect level global variables?
Well it really depends on the NUMBER of variables that you need to access. If there are a lot of variables that you need to access from anywhere within your application I'd suggest making a singleton. How to make a singleton
Here is an example on how it works made by Sachin Shanbhag
@implementation MySingleton
static MySingleton* _sharedMySingleton = nil;
+(MySingleton*)sharedMySingleton
{
@synchronized([MySingleton class])
{
if (!_sharedMySingleton)
[[self alloc] init];
return _sharedMySingleton;
}
return nil;
}
There are a many different approaches to do this:
Declare Variable in .h, like "myView.h" file and access it by importing this .h file (by
#import "myView.h"
file)Declare Variable as extern in .h, like "myView.h" file as extern
NSArray *myGlobalArray;
Then in the AppDelegate file, allocate & initialize variable:myGlobalArray = [[NSArray alloc] init];
Then just
#import "myView.h"
where you need this variable.I thin this would help you a little bit.
I just answered a similar question few days back. Use of singleton will be the best approach according to me. You can also see my answer regarding use of singleton for global variables.
You might also use appDelegate for this purpose. But I won't recommend using appDelegate. See this for clarification.
Its either u use the word extern in the header file
extern NSString* yourVar;
or u can declare it in your app delegate as u mentioned..
精彩评论