views:

52

answers:

3

Hello,

In my iPhone app, there is a setup assistant which helps users to input a lot of data. It's basically a UINavigationController with lots of UIViewControllers in it. Now, at a certain point, I want to access a variable that the user entered in the first UIViewController he saw. I could pass the variable between every UIViewController with a setter method, but I guess there is an easier way.

I would appreciate some help, Fabian

A: 

You can declare global or class variables in C style if you want to. If you want the same variable to be available in several of your sub classes of UIViewController, you'd declare it as an extern variable in the .h file of your first controller, for example:

#import <UIKit/UIKit.h>

extern NSString *myGlobalString;

@interface MyFirstViewController : UIViewController {
...

You'd then redeclare it in your .m file without the extern.

#import "MyFirstViewController.h"

NSString *myGlobalString;

@implementation MyFirstViewController 

You shouldn't redeclare it in the other .m or .h files, but you can access the variable in all files that import MyFirstViewController.h. When setting the variable, take care to release and retain it properly. It's easy to create a memory leak with this kind of global variable.

Do I not have to store a pointer to the original MyFirstViewController to access it?
fabian789
No, you don't have to store any pointer to objects to access this kind of variable, but you only get one instance of this and it's is shared between all your objects.
Ok, thanks! I'm going to try this as soon as I'm home.
fabian789
A: 

You can use a singleton instance, available from all your classes, that will handles all the information you need.

Singleton in objective-C, Wikipedia

Francois B.
A: 

Ya , there is much a easy way to handle this.....

You can take a Global Variable

In your Delegate.h file declare your variable:

@interface Smoke_ApplicationAppDelegate : NSObject {

UIWindow *window;
UINavigationController *navigationController;
NSString *messageString;  //This would be your String Variable

} @property(nonatomic,retain)NSString *messageString;

Secondly in Delegate.m file

@implementation Smoke_ApplicationAppDelegate

@synthesize window; @synthesize navigationController; @synthesize messageString; // Synthesize it over here..

This is Done .Now you can use this String Variable in All/any class you want..

To use this Global Variable.

Just import you Delegate file make the obj of it....

import "DelegateFile.h"

@implementation About

DelegateFile *appDel;

Now in Your class.m

  • (void)viewDidLoad { [super viewDidLoad];

    appDel=[[UIApplication sharedApplication]delegate];

}

Now you can access it anywhere in your class by this Object:

appDel.messageString

Just follow my Steps Carefully After giving so much pain to my finger, I am sure this is definitely going to help you.....

Have a easy life,

Ajay Sharma
Thanks, sounds good.
fabian789