12

I want store a number as a global variable. What syntax do I use, and how can other parts of my application access that variable?

jscs
  • 63,694
  • 13
  • 151
  • 195
Shawn
  • 245
  • 2
  • 3
  • 7
  • 1
    This is your [3rd post in a row](http://stackoverflow.com/questions/7080883/application-delegate-storing-files) and is not the way you should be trying to get answers. Consider editing the original post or commenting on it to keep it active Please review the [SO FAQ](http://stackoverflow.com/faq#bounty) – Joe Aug 16 '11 at 16:13
  • 1
    possible duplicate of [Storing and Accessing Methods from the AppDelegate](http://stackoverflow.com/questions/7080376/storing-and-accessing-methods-from-the-appdelegate) – Anomie Aug 16 '11 at 16:18

6 Answers6

29

For a standard global variable (not persistent when the app is terminated and restarted) add this to a header file (*.h) of your choice:

extern NSInteger MYGlobalVariable;

Then put this in the implementation file; (*.m, *.c, *.cpp):

MYGlobalVariable = 0;  // Or any other default value.

That is how you do a bread and butter global variable.

67cherries
  • 6,931
  • 7
  • 35
  • 51
PeyloW
  • 36,742
  • 12
  • 80
  • 99
  • 3
    You can also just use "#define MYGlobalVariable 0" in the .h and skip creating a .m at all. – Joel May 10 '12 at 23:06
  • 1
    @PeyloW I know this is a really old thread, but I'm not sure how to handle this: I've done `extern NSDictionary globalStuff` in my AppDelegate, and initialised it in the AppDelegate's `application:didFinishLaunchingWithOptions:` method, but when I try to compile it, I get a linker error `Undefined symbols for architecture i386`. I also reference the dictionary in other classes. Could you provide some help? – tomsmeding Aug 09 '12 at 18:38
  • @tomsmeding: you probably wanted to put "extern NSDictionary * globalStuff;" in your header file, and "NSDictionary * globalStuff;" in your source file. – jd. Sep 22 '12 at 01:34
  • ld: symbol(s) not found for architecture x86_64 clang: error: linker command failed with exit code 1 (use -v to see invocation) – swiftache Nov 11 '21 at 11:31
21

You probably want to use NSUserDefaults for this :

From anywhere in your code, you can set a value for a key :

int userAge = 21; // Just an example

NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];

if (standardUserDefaults) {
    [standardUserDefaults setObject:[NSNumber numberWithInt:userAge] forKey:@"age"];
    [standardUserDefaults synchronize];
}

And get it back from any other place :

NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
NSNumber *age = nil;

if (standardUserDefaults) 
    age = [standardUserDefaults objectForKey:@"age"];

userAge = [age intValue]

You can also set an initial value :

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSDictionary *appDefaults = [NSDictionary
    dictionaryWithObject:[NSNumber numberWithInt:13] forKey:@"age"];

[defaults registerDefaults:appDefaults];

Also, if you have complex data, you may want to create a wrapper class with setters and getters.

Julien
  • 9,312
  • 10
  • 63
  • 86
  • Make sure you set default values as well, if there's any possible way that you'll reach the second code example before the first (if you can get data before you set it). – mopsled Aug 16 '11 at 16:20
  • True, I edited my answer. You'd get nil if you don't specify value, so you can also deal with this. Nil is your friend :-) – Julien Aug 16 '11 at 16:27
14

Define the variable in AppDelegate.h file. Create a property in .h file

@property (retain, nonatomic) NSString *str;

Then synthesize in AppDelegate.m file;

@synthesize str;

Later define a variable in you project prefix.pch file

#define DELEGATE ((AppDelegate*)[[UIApplication sharedApplication]delegate])

Use the value anywhere in your project

AppDelegate *a = DELEGATE;
a.str = @"value";
NSLog(@"value of variable str : %@",a.str);
Raviraj Jadeja
  • 849
  • 6
  • 17
  • One of the best answers for that question, Delegate -> .pch -> POOM !! Thanks a lot Raviraj :) – Atef Mar 10 '14 at 15:54
  • Also if you want to add a framework which should be global and not defining it in all the classes you can write the import statement in the .pch itself. – Raviraj Jadeja Mar 15 '14 at 06:32
1

To make a Variables that can be seen by the whole files in Objective c

for example you want to set your base url one time and in each class you append on it some extra strings,

go to main.m file, because this is the place the whole app will see it. then outside main function, put your base url

NSString *baseurl = @"staging.nabdanet.com";

int main(int argc, char * argv[])
{
    @autoreleasepool {
        return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
    }
}

and when you want to access these class, all what you will do is this,

SomeClass.m

extern NSString *baseurl;

with the same name in both ;)

Atef
  • 2,872
  • 1
  • 36
  • 32
0

For persistent vars, use NSUserDefaults. This gets written on a file in the app sandbox. For session vars (non-persistent), I use a singleton class with an NSMutableDictionary property to store variables.

Ron
  • 1
  • 1
0

To declare a global variable in either objective-C or Swift, you simply declare it outside the scope of any class/interface.

Objective-C:

#import "headerFile1.h"
#import "headerFile2.h"

BOOL isTrue = true;
int x = 1;

@interface exampleInterface (){
...  
}
@end

@implementation exampleClass
...

isTrue= false; // can be used in the same way anyplace in your code
x=3; // anyplace means anyplace, even from other controllers
@end

Swift:

import UIKit

var x=45;

class SomeClass {
... 
x=0; // This is also available from anyplace in your project
...
}
Loukan ElKadi
  • 2,687
  • 1
  • 16
  • 20