在Objective-C全局变量全局变量、Objective

2023-09-08 12:21:35 作者:会离开就别深拥 i

在ActionScript中,你可以有这样的全局变量:

In Actionscript you can have global variables like this:

var number : Number = 15;

,然后使用它的方法/函数。你如何做到这一点在Objective-C,这可能吗?

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

推荐答案

记住的Objective-C是一个严格的超集的C,所以你可以声明全局变量相同的方式,你会在常规C.先在一些文件中声明它们任何函数外,然后用C 的extern 关键词在其他文件中拉这些变量在

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.

如果你想的不仅仅是C变量做到这一点,而是使用Objective-C的对象,你可以将它们存储在应用程序的委托。简单地将它们那里你会正常,那么无论什么时候你需要访问的变量:

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.