Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
482 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...