如何定义可以在应用程序中的任何位置访问的全局变量?
可能的重复:
全局 int 变量目标 c
我想创建一个全局变量。 我想在任何地方访问这个变量。
Java 等效项:
static var score:int = 0;
例如,如果我在 Game 类中定义一个全局变量。 如何访问这个全局变量呢?
Game.score ?
Possible Duplicate:
Global int variable objective c
I would like to create a global variable.
I want to access to this variable anywhere.
The Java equivalent:
static var score:int = 0;
For example if I define a global variables into the Game class.
How to access to this global variable?
Game.score ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您的应用程序中有多个视图,并且在这种情况下您希望每个视图都可以访问一个变量,那么您应该始终创建一个模型/数据类并在其中定义该变量。像这样的东西:
Objective-C:
现在在你的视图控制器中,你需要调用这个方法:
每个视图控制器都可以访问这个变量。您只需创建 Data 类的实例。
Swift:
用法:
DataClass.sharedManager.str
使用
dispatch_once
用法:
DataClass.sharedManager.str< /代码>
If you are having multiple views in your application, and in that case you want to have a variable accessible to every view, you should always create a Model/Data class and define the variable in it. Something like this :
Objective-C :
Now in your view controller you need to call this method as :
This variable will be accessible to every view controller. You just have to create an instance of Data class.
Swift :
Usage :
DataClass.sharedManager.str
Using
dispatch_once
Usage :
DataClass.sharedManager.str
Objective-C 不直接支持“类变量”。相反,您可以创建一个在类文件范围内有效的变量,并使用类方法访问它。
Objective-C does not have support for "class variables" directly. Instead, you can create a variable which is valid for the scope of the class's file and access it using class methods.
在 iOS 项目中实现全局变量(尽管这些不是真正的全局变量)的首选方法是在应用程序委托中创建一个属性,然后从每个类访问该属性。
编辑:重新阅读您的问题,看来我误解了您的问题,ughoavgfhw的答案可能就是您正在寻找的。他是对的,Objective-C 中没有类变量这样的东西,所以你必须创建一个常规的 C 静态变量,然后创建类方法(用
+
表示,而不是-
) 用于设置和获取。虽然一般来说,当我在应用程序中需要“全局”变量时,我会创建单例类来容纳它们及其相关方法(因此应用程序委托不会因不相关的属性而溢出),或者如果它是一个较小的项目,我只使用应用程序委托(也是一个单例类)而不是单独的单例。不过,如果静态变量加类 setter/getter 方法更适合您的需求,那么它没有任何问题。
The preferred way to implement global variables in an iOS project (though these aren't true global variables), is to create a property in the application delegate, then just access that property from each of your classes.
EDIT: Re-reading your question, it looks like I misinterpreted your question, and ughoavgfhw's answer is probably what you're looking for. He's correct, there is no such thing as a class variable in Objective-C, so you have to create a regular C static variable, then create class methods (denoted by the
+
rather than a-
) for setting and getting.Though generally, when I need "global" variables in an app, I create singleton classes to house them and their related methods (so the app delegate doesn't overflow with unrelated properties), or if it's a smaller project I just use the application delegate (which is a also a singleton class) rather than separate singletons. Though there's nothing wrong with the static variable plus class setter/getter approach if that works better for your needs.