0

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?

creatando
  • 25
  • 1
  • 4
  • try any one at a time or both this `var selectedP: Int!` and `self.selectedP = sender.tag`. I am just saying I haven't tried it practically. – knownUnknown Mar 01 '17 at 04:30
  • @creatando setPlayer should be called in your IBAction you get your value in variable only when you perform your action.Before that you can not call setPlayer method. – Tushar Sharma Mar 01 '17 at 06:19

2 Answers2

0

Correct me if I'm wrong, but I believe you set your variable as self.selectedP, not selectedP. I'm not familiar with swift, but this concept is fairly universal. In python:

class foo():
    def setBar():
        self.bar = True
    print(str(self.bar)) #prints True
    print(str(bar))      #throws error
0

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.

creatando
  • 25
  • 1
  • 4