views:

519

answers:

1

In Actionscript you can have global variables like this:

var number : Number = 15;

And then use it in a method/function. How do you do that in Objective-c, is it possible?

+4  A: 

Remember that Objective-C is a strict superset of C, so you can declare global variables the same way you would in regular C. First declare them in some file outside of any function, then use the C extern keyword in other files to pull those variables in.

If you want to do this with more than just C variables, but rather use Objective-C objects, you can store them in the application's delegate. Simply set them there as you would normally, then whenever you need to access the variable:

// Assuming your app delegate is of class YourAppDelegate and
// has an NSString* variable called globalString:
YourAppDelegate *appDelegate = 
    (YourAppDelegate *)[[UIApplication sharedApplication] delegate];
NSString *someGlobalString = [appDelegate globalString];

You may also find it beneficial to declare the variable static in the app delegate.

Tim