iOS getting value of variable from another ViewController

I have 2 View Controllers.

"FirstVieController"

"TableViewController"


Code of FirstViewController:

class FirstViewController: UIViewController {

    var category: String = ""

    override func viewDidLoad() {
        super.viewDidLoad()
    
    }

    @IBAction func buttonOne(_ sender: Any) {
        category = "buttonOne"
    }
    @IBAction func buttonTwo(_ sender: Any) {
        category = "buttonTwo"
    }
    @IBAction func buttonThree(_ sender: Any) {
        category = "buttonThree"
    }

}


Now I want to get the value of var category on TableViewController

I tried it like this:

var getCategory: String = FirstViewController.category

but following error occurs:

Instance member 'category' cannot be used on type 'FirstViewController'


How can I get the value of category of FirstViewController in TableViewController?

Accepted Reply

You try to read an instance property as a class property, hence the error.


You have several options :


- if you segue from FirstViewController, to TableViewController, just pass the value in prepare for segue.

- use delegation ; have a look here if you need to see how : https://forums.developer.apple.com/thread/111569

- reference the instance of FirstViewController in the tableViewController

Replies

You try to read an instance property as a class property, hence the error.


You have several options :


- if you segue from FirstViewController, to TableViewController, just pass the value in prepare for segue.

- use delegation ; have a look here if you need to see how : https://forums.developer.apple.com/thread/111569

- reference the instance of FirstViewController in the tableViewController

thank you for your help.

The best way for me as a beginner was to pass the value in prepare for segue function.