Question

I searched the internet and more than 20 topics about global variables, I just couldn't find the one I need.

  • Will use it in an iOS application.
  • I want the variable to be accessible from all views.
  • I want a few views to be able to change that variable.
  • Preferably don't want to mess with segues.
Was it helpful?

Solution

You could do what is suggesting, add a variable in AppDelegate and then fetch it from your view controllers like this:

AppDelegateNeme *ap = (AppDelegateNeme *)[[UIApplication sharedApplication] delegate];
ap.yourVar = smth

As you can see in code above, you are accessing shared instance of UIApplication and just by casting it to your AppDelegate class you can reach your "global" variable. But I personally don't see this as the best solution. What happens is that you need to include your app delegate in every UIViewController, and chances are that you already included that UIViewController in your AppDelegate so you could end up looking at recursive includes or a very messy code.

Cleaner approach would be to create a class to store your global variables, just add a file and for a class choose NSObject. Then you can create singleton object of that class or you can just define class variables and class methods (the one with +) to store and fetc values from your "global vars".

In this way your code will be mode readable and you will never have any include problems, as long as you don't start including stuff in that class.

Example:

//GlobalClass.h
@interface GlobalClass : NSObject

@property (nonatomic) BOOL someBool;

// example wit a singleton obj:
+ (GlobalClass *)globalClass;

// example with class methods
+(int)GetMyVar;
+(void)SetMyVar:(int)var;

//GlobalClass.m
static int MyVar;

@synthesize someBool;

static GlobalClass *globalClass = nil;

+ (GlobalClass *)globalClass
{
    if (globalClass == NULL)
    {
        // Thread safe allocation and initialization -> singletone object
        static dispatch_once_t pred;
        dispatch_once(&pred, ^{ globalClass = [[GlobalClass alloc] init]; });
    }
    return globalClass;
}

+(int)GetMyVar
{
    return MyVar;
}
+(void)SetMyVar:(int)var
{
    MyVar = var;
}

So from outside (from your viewcontroller): To create singleton and set our bool property:

//set var:
[[GlobalClass globalClass] setSomeBool:YES];
// get 
BOOL b = [[GlobalClass globalClass] someBool];

OR use class methods (don't need to create singletone obj)

// set
[GlobalClass SetMyVar:5];
// get
int num = [GlobalClass GetMyVar];

Hope this helps...

OTHER TIPS

In app delegate header

extern NSString* const globalVariable1;

in app delegate m file

NSString* const globalVariable1 = @"My Value";

You can access this global variable in any view controller.

this is just for string.

int const for integer.

just BOOL for boolean.

Hope this helps

For swift I used this method:

struct MyStyles {

static let ThemeColor = UIColor(red: 41/255, green: 156/255, blue: 253/255, alpha: 1.0)
static let ThemeSecondColor = UIColor.whiteColor()
static let ThemeGrayLineColor = UIColor(red: 128/255, green: 128/255, blue: 128/255, alpha: 1.0)
static let ThemeMyCommentsColor = UIColor(red: 219/255, green: 238/255, blue: 255/255, alpha: 1.0)
static let ThemeCommentedToMeColor = UIColor(red: 227/255, green: 232/255, blue: 235/255, alpha: 1.0)

static let ThemeFontName = "HelveticaNeue-Light"
static let ThemeFontNameBold = "Helvetica-Bold"

static let ScreenWidth = UIScreen.mainScreen().bounds.size.width
static let ScreenHeight = UIScreen.mainScreen().bounds.size.height
static let StatusBarHeight = UIApplication.sharedApplication().statusBarFrame.size.height

static func largeButton(#title: String, action: String, target: UIViewController) -> UIButton {

    let button = UIButton(frame: CGRect(x: 0, y: ScreenHeight*9/10, width: ScreenWidth, height: ScreenHeight/10))
    button.setTitle(title, forState: UIControlState.Normal)
    button.backgroundColor = ThemeSecondColor
    button.tintColor = ThemeColor
    button.titleLabel?.font = UIFont(name: ThemeFontName, size: 50)
    button.setTitleColor(ThemeColor, forState: UIControlState.Normal)
    button.addTarget(target, action: Selector(action), forControlEvents: UIControlEvents.TouchUpInside)
    return button
}

}

I access them like this from other classes:

var color = MyStyles.ThemeColor

You should declare your 'global' variables in your Application Delegate class.

This way you can ensure that all your viewsControllers etc will be able to access them.

For me it's probably the most elegant solution, when you need access to one of these vars you can just get a reference to your app delegate.

Create a singleton class. Add all global variables as read/write properties. Create the singleton instance when your app starts, typically inside application:didFinishLaunchingWithOptions: method. Using this singleton instance you can now share information throughout your app.

You may need to thing about making the properties thread safe in case your app will access these in a multithreaded environment.

Hope that helps!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top