t0re199
t0re199

Reputation: 730

How to set a variable value in another class in Swift

How can I add a value to a variable in a class myClass2 from another class myClass in swift?

I have already tried something like myClass2().myvariable = "value", but this didn't work; my variable value is still nil. here's the code:

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";
    }

}

Upvotes: 1

Views: 11096

Answers (1)

rdelmar
rdelmar

Reputation: 104092

You're creating an instance of myViewController2 called myClass instance, but that's not the instance that you push onto the stack -- the instance being pushed is view2. So the last line in toView2Pressed should be,

view2.myVariable = "my new value"

You should delete the line, let myClassInstance = myViewController2(). It serves no purpose. You should also start your class names with a capital letter.

Upvotes: 5

Related Questions