1

I'm trying to access a var which located in another class(ViewController), but I cannot access answeredCorrectly variable in LastView class. How can I access it and when I call answeredCorrectly like that(marked with 1) is it going to use the default instance of ViewController?

I tried that(LastView.swift)

import Foundation
import UIKit



class LastView: ViewController {

    @IBOutlet weak var numberLabel: UILabel!

    func assignLabelToCount(){
        numberLabel.text = "\(answeredCorrectly)"
    }

}

Whole View Controller

import UIKit


class ViewController: UIViewController, UITextFieldDelegate {



    @IBOutlet weak var questionLabel: UILabel!
    @IBOutlet weak var answerBox: UITextField!
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

       answerBox.addTarget(self, action: "textFieldDidChange:", forControlEvents: UIControlEvents.EditingChanged)




    }

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



    var questionShowing = ""
    var answerForControl = 0
    @IBAction func newButton() {
        var question = getQuestion()
        questionShowing = question.0
        answerForControl = question.1
        questionLabel.text = questionShowing
        var timer = NSTimer.scheduledTimerWithTimeInterval(2, target: self, selector: Selector("endGame"), userInfo: nil, repeats: false)
        print()
    }

    func print(){
        println("\(questionShowing) >>>>>> \(answerForControl)")
    }





        var answeredCorrectly = 0


    func textFieldDidChange(textField: UITextField) {
        var answerInInt = String(stringInterpolationSegment: answerForControl)
        var answer: String? = String(answerInInt)
        if answerBox.text == answer {
            newButton()
            answeredCorrectly++
            answerBox.text = ""
        } else {
        }
    }

    func endGame(){

        println("Count of correct answers: \(answeredCorrectly)")
        answeredCorrectly = 0
        LastView().assignLabelToCount()
        performSegueWithIdentifier("toEnd", sender: nil)
    }

    func getQuestion() -> (String, Int){...}


}
Encul
  • 93
  • 1
  • 10
  • possible duplicate of [How do you share data between view controllers and other objects in Swift?](http://stackoverflow.com/questions/29734954/how-do-you-share-data-between-view-controllers-and-other-objects-in-swift) – nhgrif Jun 25 '15 at 12:28

4 Answers4

0

declare variable numberLabel as public

meena
  • 189
  • 1
  • 3
  • 12
  • This would only matter if he's got multiple frameworks in his workspace. By default, the variable is `internal` which means it can be accessed by everything else in the framework... – nhgrif Jun 25 '15 at 12:29
0

You need to create instance of that class to access the variable.

Ex:

var lastViewInstance: LastView = LastView() // Declare in the class in which you want to access the variable

lastViewInstance.numberLabel.text = "Access from Another class"

This is how you can access any variable or outlet!

Sohil R. Memon
  • 9,404
  • 1
  • 31
  • 57
  • 2
    I won't down vote because this technically isn't wrong, but it's almost certainly not actually right. – nhgrif Jun 25 '15 at 12:27
0

You can store your object into disk by using NSUserDefaults and you can use it this way:

Store your object to NSUserDefaults:

NSUserDefaults.standardUserDefaults().setObject("YouObjectValue", forKey: "YourKey")

After that you can access it anywhere into your project this way:

let yourVar: AnyObject? = NSUserDefaults.standardUserDefaults().objectForKey("YourKey")

Hope it will help you.

Dharmesh Kheni
  • 71,228
  • 33
  • 160
  • 165
0

There are a couple of things you could do, if you want to utilize inheritance, go ahead and try this kind of structure:

class ViewController : UIViewController {
  //the var you want to access
  var answeredCorrectly: Int = ViewController().answeredCorrectly
  //your other code
  //....
}

then, inherit the class, since your class LastView inherits ViewController, any class that inherits ViewController will now have access to UIViewController.

Note

If you haven't changed the subclass of your ViewController, it should be UIViewController by default.

let's inherit the class for your LastView class:

class LastView : ViewController {
  //now your LastView class inherits from ViewController, which also inherits
  //from UIViewController, it's like a big chain of classes
  @IBOutlet weak var numberLabel: UILabel!

  func assignLabelToCount() {
    numberLabel.text = "\(answeredCorrectly)"
  }
}

The function just simply assigns your variable answeredCorrectly, which is located in ViewController.

Justin Rose
  • 1,041
  • 7
  • 14
  • When I did what you wrote I got an runtime error. I also added LastView().assignLabelToCount() this on segue function. I got the same error here too. numberLabel.text = "\(answeredCorrectly)" //Thread 1:EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0) – Encul Jun 25 '15 at 13:17
  • Could you share more of your code, and where you're getting the error? @Encul – Justin Rose Jun 25 '15 at 13:55
  • I edited the question and added more code @Justin Rose – Encul Jun 25 '15 at 14:03