如何在Swift中的另一个类中设置变量值

时间:2015-01-14 18:58:29

标签: ios class variables swift uiviewcontroller

如何在swift中从另一个类myClass2向类myClass中的变量添加值?

我已经尝试了类似myClass2().myvariable = "value"的内容,但这并没有奏效;我的变量值仍为nil。这是代码:

myViewController2:

import UIKit

class MyViewController2: UIViewController {

    var myVariable : String?;

    @IBOutlet weak var display: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func showPressed(sender: AnyObject) {
        display.text = myVariable;
    }

}

的ViewController:

import UIKit

class ViewController: UIViewController {

    let myClassInstance = myViewController2();
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func toView2Pressed(sender: AnyObject) {

        let view2 = self.storyboard?.instantiateViewControllerWithIdentifier("view2") as myViewController2;
        self.navigationController?.pushViewController(view2, animated: true);
        myClassInstance.myVariable = "my new value";
    }

}

1 个答案:

答案 0 :(得分:5)

您正在创建一个名为myClass实例的myViewController2实例,但这不是您推入堆栈的实例 - 正在推送的实例是view2。所以toView2Pressed的最后一行应该是,

view2.myVariable = "my new value"

你应该删除该行,让myClassInstance = myViewController2()。它没有任何意义。您还应该用大写字母开始您的班级名称。