1

I want to use global variables and objects for the iphone project.

I have created NSobject class and defined like below:

.h File:

#import <Foundation/Foundation.h>

@interface GlobelClass : NSObject

extern NSString *mystr;

extern NSMutableArray *Arrdata;

@end

.m File:

#import "GlobelClass.h"

@implementation GlobelClass

NSString *mystr;
NSMutableArray *Arrdata;
@end

What is the best way Or should I use singleton pattern like below link answer: Using global variables in Objective-C

Please share thoughts?

Community
  • 1
  • 1
Jagdev Sendhav
  • 2,875
  • 4
  • 15
  • 24

1 Answers1

0

One of the way to use global variable in the application is:

You can use App Delegate class itself :

.h file:

AppDelegate: UIResponder <UIApplicationDelegate> {

}

@property(nonatomic,strong) NSString* strUserID;

.m file:

@synthesize strUserID;

Now you can access strUserID as global variable in your UIViewController as:

ABCProjectAppDelegate *appDelegate = (ABCProjectAppDelegate*) [[UIApplication sharedApplication] delegate];

You can set value:

appDelegate.strUserID = @"Test";

Get Value:

NSString *strId = appDelegate.strUserID;

:)

Wain
  • 118,658
  • 15
  • 128
  • 151
Gaurav
  • 299
  • 4
  • 15
  • 1
    The app delegate is for app level delegation of responsibility. Not a store of arbitrary code / constants / settings. – Wain Feb 17 '14 at 08:17
  • You can create one header file for the global variables. You can define global variables on that file. Is that approach you have thought before? – Gaurav Feb 17 '14 at 08:23