1

Possible Duplicate:
How to use global variables in Objective-C?

In my Login.m file, I have

NSString *userName = txtUsername.text; // this is getting the text from the username text field and storing it in userName

The problem is that I need to access the variable userName from different classes also and so I need to declare it as a global variable. What is the best way of doing this ?

Community
  • 1
  • 1
Ashish Agarwal
  • 14,555
  • 31
  • 86
  • 125
  • This question suffers from the [XY problem](http://meta.stackexchange.com/questions/66377/). As for the solution it describes, [globals are bad](http://c2.com/cgi/wiki?GlobalVariablesAreBad). As an alternative, see [Objective-C: Allocation in one thread and release in other](http://stackoverflow.com/q/4698273/90527) for an example implementation of a class variable with accessors. – outis Nov 26 '11 at 04:30

3 Answers3

1

One option is to make it an instance variable in the Application Delegate. The Application Delegate can easily be accessed from other class instances. This is somewhat better as global variables are not a good design.

zaph
  • 111,848
  • 21
  • 189
  • 228
0

What I would do is forget about the variable, but in these other classes refer to txtUsername.txt, otherwise you're making a copy of the text which you're trying to keep updated hoping that you haven't missed anything.

So in your .h file, you put

{

UITextField *txtUsername;

}

as I assume you already have.

Then:

@property (nonatomic, retain) UITextField *txtUsername;

And then in your .m file, put at the top, under the @implementation line:

@synthesize txtUsername;

Then in the .m file that you want to reference it in, go to it's .h file and put:

#import "Login.h"

at the top, with the other import lines. Then put:

{

Login *login;

}

This creates a variable called login. You can then wire this up to your xib if you're using one, or init it in code if you're not. Then, when you want the text, you simply put:

login.txtUsername.text;
Andrew
  • 15,935
  • 28
  • 121
  • 203
0

Consider a singleton class which will hold your global variables.

To declare a singleton class, take a look at the following example and, or see here

+(Constants *) instance {
    @synchronized(self) {
        if (gInstance == NULL) {
            gInstance = [[self alloc] init];
        }
    }

    return gInstance;
}


-(id) init {

    if (gInstance != NULL) {
        return gInstance;
    }

    self = [super init];

    if (self) {
      // do something clever
    }
    gInstance = self;
    return gInstance;
}
James Raitsev
  • 92,517
  • 154
  • 335
  • 470