0

I have 2 classes in 2 different Swift files (UIViewController).

In the first class I declare a var:

class HomeScreen: UIViewController {

var Score = 0
let blackColor = UIColor.blackColor()

@IBOutlet weak var ScoreLabel: UILabel!

override func viewDidLoad() {
    super.viewDidLoad()
ScoreLabel.text = "Score: \(Score)"

}}

In the second class/file I want to increment this var:

class SecondVC: UIViewController {

@IBAction func ButtonPressed(sender: AnyObject) {

    HomeScreen().Score++
}}

As you can see, I want to display the Score-var in a Label. BUT there always stays "0"

What is the mistake?!

Thanks!!!

2 Answers2

1

Your code HomeScreen().Score++ is creating a new instance and incrementing the score variable of that new instance, then that instance is being thrown away.

You need a reference to the actual HomeScreen instance being used. I recommend Passing Data between View Controllers as a reference on a few ways to do this.

Community
  • 1
  • 1
Acey
  • 8,048
  • 4
  • 30
  • 46
0

This:

@IBAction func ButtonPressed(sender: AnyObject) {

    HomeScreen().Score++
}

You are creating a new instance of HomeScreen, incrementing it's value, and then, at the end of the method, it is going out of scope, so all changes are lost.

You should be changing the values on an initialised object instead, something like instead:

@IBAction func ButtonPressed(sender: AnyObject) {

    // homeScreen is a reference to an already existing local variable
    homeScreen.Score++

}
Anorak
  • 3,096
  • 1
  • 14
  • 11