Sharing data between multiple view controllers wit

2019-07-27 22:36发布

问题:

I'm doing a QR code scanner quiz app where users must get a score of 10 from doing 10 questions. After a user the 1st qn, the score will plus 1 and it will revert them back to the qr scanner page where they must scan the QR code for the next qn. The problem is the passing of the score data. Is there a way to do it without segue?

This is my qn1controller

import UIKit

class Quiz1Controller: UIViewController {

    @IBOutlet var question: UILabel!
    @IBOutlet var button1: UIButton!
    @IBOutlet var button2: UIButton!
    @IBOutlet var button3: UIButton!
    @IBOutlet var button4: UIButton!
    @IBOutlet var LabelEnd: UILabel!
    @IBOutlet var scorelabel: UILabel!
    var score = Int()
    var CorrectAnswer = String()

    override func viewDidLoad() {
        super.viewDidLoad()

        RandomQuestions()
    }

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

    func RandomQuestions(){

        var RandomNumber = arc4random() % 1
        RandomNumber += 1

        switch(RandomNumber){
        case 1:
            question.text = "Who is the current Deputy Chairman of People's Association?"
            button1.setTitle("Lee Hsien Loong", for: .normal)
            button2.setTitle("Chan Chun Sing", for: .normal)
            button3.setTitle("Goh Chok Tong", for: .normal)
            button4.setTitle("Goh Khen Swee", for: .normal)
            CorrectAnswer = "2"
            Hide()
            break
        default:
            break
        }
    }

    func Hide(){
        LabelEnd.isHidden = true
    }
    func UnHide(){
        LabelEnd.isHidden = false
    }

    @IBAction func Button1(_ sender: Any) {
        UnHide()

        if (CorrectAnswer == "1"){
            self.performSegue(withIdentifier: "correct", sender: self)
        }
        else {
            LabelEnd.text = "Incorrect Answer! Try again"
        }
    }

    @IBAction func Button2(_ sender: Any) {
        UnHide()

        if (CorrectAnswer == "2"){
            score = score + 1
            scorelabel.text = "Score:\(score)"
            self.performSegue(withIdentifier: "correct", sender: self)            
        }
        else {
            LabelEnd.text = "Incorrect Answer! Try again"
        }
    }

    @IBAction func Button3(_ sender: Any) {
        UnHide()

        if (CorrectAnswer == "3"){
            self.performSegue(withIdentifier: "correct", sender: self)
        }
        else {
            LabelEnd.text = "Incorrect Answer! Try again"
        }
    }

    @IBAction func Button4(_ sender: Any) {
        UnHide()

        if (CorrectAnswer == "4"){
            self.performSegue(withIdentifier: "correct", sender: self)
        }
        else {
            LabelEnd.text = "Incorrect Answer! Try again"
        }
    }

}

And this is my qn2 controller

import UIKit

class Quiz2Controller: UIViewController {

    @IBOutlet var question: UILabel!
    @IBOutlet var button1: UIButton!
    @IBOutlet var button2: UIButton!
    @IBOutlet var button3: UIButton!
    @IBOutlet var button4: UIButton!
    @IBOutlet var LabelEnd: UILabel!
    @IBOutlet var scorelabel: UILabel!
    var score = Int()
    var CorrectAnswer = String()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        RandomQuestions()
    }

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

    func RandomQuestions(){

        var RandomNumber = arc4random() % 1
        RandomNumber += 1

        switch(RandomNumber){
        case 1:
            question.text = "Who is the founder of People's Association?"
            button1.setTitle("Lee Hsien Loong", for: .normal)
            button2.setTitle("Lee Kuan Yew", for: .normal)
            button3.setTitle("Goh Chok Tong", for: .normal)
            button4.setTitle("Goh Khen Swee", for: .normal)
            CorrectAnswer = "1"
            Hide()
            break
        default:
            break
        }
    }

    func Hide(){
        LabelEnd.isHidden = true
    }
    func UnHide(){
        LabelEnd.isHidden = false
    }

    @IBAction func Button1(_ sender: Any) {
        UnHide()

        if (CorrectAnswer == "1"){
            score = score + 1
            scorelabel.text = "Score:\(score)"
            self.performSegue(withIdentifier: "correct", sender: self)
        }
        else {
            LabelEnd.text = "Incorrect Answer! Try again"
        }
    }

    @IBAction func Button2(_ sender: Any) {
        UnHide()

        if (CorrectAnswer == "2"){
            self.performSegue(withIdentifier: "correct", sender: self)
        }
        else {
            LabelEnd.text = "Incorrect Answer! Try again"
        }
    }

    @IBAction func Button3(_ sender: Any) {
        UnHide()

        if (CorrectAnswer == "3"){
            self.performSegue(withIdentifier: "correct", sender: self)
        }
        else {
            LabelEnd.text = "Incorrect Answer! Try again"
        }
    }

    @IBAction func Button4(_ sender: Any) {
        UnHide()

        if (CorrectAnswer == "4"){
            self.performSegue(withIdentifier: "correct", sender: self)
        }
        else {
            LabelEnd.text = "Incorrect Answer! Try again"
        }
    }

}

Story Board :

回答1:

Delete Seague and do it like as follow. Assume you want to share NSMutableDictionary.

Just take a variable as type you want to share with viewController.

For Exa. you want to share data with ShareViewController then take a variable like

var Dict_data = NSMutableDictionary()

Now Where you want to navigate, just do like Assume It's your ShareViewController. Remember dont forget to give identifier of ShareViewController into StoryBoard.

    let PV = self.storyboard?.instantiateViewController(withIdentifier: "ShareViewController") as! ShareViewController
    PV.data = dict_share_date 
    self.navigationController?.pushViewController(PV, animated: true)

Here dict_share_data is your NSMutableDictionry. You can take any type but remember both side types must same. or you can do type casting.



回答2:

You can use AppDelegate to share data between multiple Viewcontrollers. You can always save ,update and retrieve data defined in AppDelegate of your App. Here is my previous ans to use it efficiently to use Appdelegate.Do let me know if you need Swift version .

In your AppDelegate define your variable as

class AppDelegate: UIResponder, UIApplicationDelegate {
  var window: UIWindow?
  var points : String? // Declare your object
  .... other methods
}
//You can access the property to save and retrieve your file. You can save 
let app = UIApplication.shared.delegate as! AppDelegate
app.points = "yourString"

 Yo can read properties from any viewcontroller as per your requirement as 

let app = UIApplication.shared.delegate as! AppDelegate
let points = app.points?

You can also use NSNotificationCenter to share data in multiple viewcontoller. Do let me know if you have queries regrading implementing the same.

If you need to pass data from one viewcontroller to another while navigation you can also use instantiation of viewcontoller using storyboard id as @Jeetendra explains in his ans.