Search code examples
iosswiftviewwithtag

Variable not storing?


I am currently developing a tactical screen app where one can access a database to add to add players into their screens. The database is working fine, I am now trying to pass over player information into the selected position. The player information passes over fine, but I am now having trouble with trying to implement that player information into the selected position:

var selectedP: Int?

@IBAction func selectAPlayer(_ sender: UITapGestureRecognizer) {
    self.selectedP = sender.view!.tag
    //print (selectedP!)
}

Above is the method which demonstrates how I am trying to save the selected position's tag with selectedP, so I can access its subviews. The correct tag prints out in the above method. However, when I try to call it in another method, the variable returned is always nil. I'm not exactly sure what the problem is. Here is the method where I try to call the selectedP variable:

func setPlayer () {
        //print(selectedP!)
    }

Simply printing selectedP crashes the program as it is obviously equivalent to nil. Is there anything I am doing wrong?

I must note that the setPlayer() method is called by a segue from another class which is essentially a View Player class. This is shown as a popover in the application. I'm not sure that if you call a popoverController the variables essentially get restored?


Solution

  • Figured it out. Had to pass over the variable to the popover, and then back. Here's how I did it in a more generic way:

        let viewController = "addPopover"
        let storyboard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
        let vc = storyboard.instantiateViewController(withIdentifier: viewController) as? PopoverViewController
    // Above we get the popover, below we set a variable in that popover's class.
        vc?.varThatNeedsToBeStored = sender.view!.tag
    

    Then in my prepare segue method in the popover class:

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        let nextScene = segue.destination as? TacticalCentreViewController
        nextScene?.varThatNeedsToBeStored = varThatNeedsToBeStored
    }
    

    This now returns the correct tag value.