1

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?

Aleem
  • 3,173
  • 5
  • 33
  • 71

3 Answers3

2

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;
}
Jose Luis
  • 3,307
  • 3
  • 36
  • 53
2

There are a many different approaches to do this:

  1. Declare Variable in .h, like "myView.h" file and access it by importing this .h file (by #import "myView.h" file)

  2. 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];

  3. Then just #import "myView.h" where you need this variable.

    I thin this would help you a little bit.

Nitish
  • 13,845
  • 28
  • 135
  • 263
Suraj Mirajkar
  • 1,369
  • 10
  • 23
0

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..

sicKo
  • 1,241
  • 1
  • 12
  • 35