Swift:ViewController中的Access变量 [英] Swift : Access variable in ViewController

查看:101
本文介绍了Swift:ViewController中的Access变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有按钮,索引和按下按钮时调用的函数的视图控制器,下面是代码示例:

I have a View Controller with a button, an index, and a function thats called when the button is pressed, here is an example of the code:

查看控制器:

func buttonPressed(){

index++

}

然后我有一个类,我想从View Controller中访问和打印索引

Then i have a class in which i want to access and print the index from the View Controller

类:

print("Index is \(ViewController().index)")

显然这不起作用,有谁知道我怎么能访问它?我无法真正实例化它,因为它的ViewController以及它不会是相同的索引。我认为。

Obviously this doesn't work, does anyone know how I can access this? I can't really instantiate it because its a ViewController as well as it will not be the same index.I think.

推荐答案

您可以将索引保存到NSUserDefaults或plist文件。尝试使用getter和setter使其自动保持如下:

You can save your index to NSUserDefaults or to a plist file. Try using a getter and a setter to make it persist automatically as follow:

Xcode 8.3.3•Swift 3.1.1

extension UserDefaults {
    var indexA: Int {
        get {
            return integer(forKey: "indexA")
        }
        set {
            set(newValue, forKey: "indexA")
        }
    }
}

用法:

加载它

let indexA = UserDefaults.standard.indexA

设置/更改

UserDefaults.standard.indexA = 10

这篇关于Swift:ViewController中的Access变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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