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 project level global variables?
3 Answers
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;
}

- 3,307
- 3
- 36
- 53
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.

- 13,845
- 28
- 135
- 263

- 1,369
- 10
- 23
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..

- 1,241
- 1
- 12
- 35