如何快速将另一个类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";
    }

}

最佳答案

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

view2.myVariable = "my new value"

您应该删除这一行,让myClassInstance = myViewController2()。它没有任何目的。您还应该以大写字母开头 class 名称。

07-24 09:51