如何定义可以在我的应用程序中的任何位置访问的全局变量? [英] How to define a global variable that can be accessed anywhere in my application?

查看:498
本文介绍了如何定义可以在我的应用程序中的任何位置访问的全局变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

全局int变量目标c

我想创建全局变量。
我想在任何地方访问这个变量。

I would like to create a global variable. I want to access to this variable anywhere.

Java等价物:

static var score:int = 0;

例如,如果我将全局变量定义到Game类中。
如何访问这个全局变量?

For example if I define a global variables into the Game class. How to access to this global variable?

Game.score ?


推荐答案

如果您的应用程序中有多个视图,并且在这种情况下,您希望每个视图都可以访问一个变量,您应该始终创建一个Model / Data类并在其中定义变量。这样的事情:

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:

//DataClass.h      
@interface DataClass : NSObject {    

    NSString *str;
}

@property(nonatomic,retain)NSString *str;    
+(DataClass*)getInstance;    
@end  


//DataClass.m    
@implementation DataClass    
@synthesize str;

static DataClass *instance = nil;

+(DataClass *)getInstance
{    
    @synchronized(self)    
    {    
        if(instance==nil)    
        {    
            instance= [DataClass new];    
        }    
    }    
    return instance;    
}    

现在在视图控制器中,您需要将此方法称为:

Now in your view controller you need to call this method as :

DataClass *obj=[DataClass getInstance];  
obj.str= @"I am Global variable";  

每个视图控制器都可以访问此变量。您只需要创建一个Data类的实例。

This variable will be accessible to every view controller. You just have to create an instance of Data class.

Swift:

class DataClass {

    private var str: String!

    class var sharedManager: DataClass {
        struct Static {
            static let instance = DataClass()
        }
        return Static.instance
    }
}

用法: DataClass.sharedManager.str

使用 dispatch_once

Using dispatch_once

class DataClass {

    private var str: String!

    class var sharedInstance: DataClass {
        struct Static {
            static var onceToken: dispatch_once_t = 0
            static var instance: DataClass? = nil
        }
        dispatch_once(&Static.onceToken) {
            Static.instance = DataClass()
        }
        return Static.instance!
    }
}  

用法: DataClass.sharedManager .str

这篇关于如何定义可以在我的应用程序中的任何位置访问的全局变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆