AppDeveloper AppDeveloper - 2 months ago 4x
Objective-C Question

Making NSString global to whole project iPhone

In my iPhone application, on login to web services I get a session ID which gets changed on every login. I want to use that session ID for y other view controllers so that I would not have to use username password again and again and also I have to the session ID with the other links of web services to get the required JSON data to iPhone.

Should I define it as a macro or there is another way to do this.


If it can be done with macro then how can i achieve this?

On login url used as:

NSString *urlAsString = [NSString stringWithFormat:@"http://url/rest/mobile/session"];

NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];

[urlRequest setTimeoutInterval:30.0f];

[urlRequest setHTTPMethod:@"POST"];

[urlRequest addValue:user forHTTPHeaderField:@"uid" ];
[urlRequest addValue:password forHTTPHeaderField:@"passwd" ];

When getting data for other views:

NSString *urlAsString = [NSString stringWithFormat:@"http://url/rest/assetgroups/7e5085390e1877fd83f7346093c8304b"];

Please let me have your suggestions


As a Global Variable

Since Objective-C is a superset of C, one approach is to simply make a global variable, just like you would in C. You want to declare the variable in a header file, like this:


extern NSString *sessionId;

Any .m file that needs to use sessionId can #import "Globals.h" to get the declaration.

You also need to define the variable in one of your .m files. For example, you could add this to main.m, outside of any function definition:


NSString *sessionId;

As an Application Delegate Property

Another approach is to make the variable be a property of your application delegate, since that is a globally-accessible object already. You need to declare it in AppDelegate.h:


@interface AppDelegate

@property (strong, nonatomic) NSString *sessionId;

// other properties and methods of AppDelegate here


and you synthesize it in AppDelegate.m:

@implementation AppDelegate {
    // ivars here

@synthesize sessionId = _sessionId;

// Rest of AppDelegate method definitions and synthesizers here


and you can access the property like this:

((AppDelegate *)[UIApplication sharedApplication].delegate).sessionId = whatever();
NSLog(@"session id = %@", ((AppDelegate *)[UIApplication sharedApplication].delegate).sessionId);