简体   繁体   中英

Having trouble initializing variable

I'm trying to initialize a variable in a view controller before that view controller takes over the view, and it seems no matter how I try to initialize it, it doesn't work and the software runs as if the value is the default value. Part of the problem seems to be the view that contains the variable in question is nil when I try to set the variable's value. I don't know why this is. Any help would be appreciated. Thanks! Here is my code:

override func setStartPosition()
{
    if sessionNameIndex != nil
    {
        if let curSession = ShareData.sharedInstance.sessionDataObjectContainer[sessionNames[sessionNameIndex]]
        {
            initialValue = YesNo(rawValue: (curSession.currentValue))

            if mySessionDisplay == nil
            {
                mySessionDisplay = SessionDisplayView(frame: self.view.frame)
                if mySessionDisplay == nil
                {
                    var shouldneverbehere = 0  //Always goes here!
                }
                else
                {
                    mySessionDisplay.onView(index: 2, sessionName: sessionNames[sessionNameIndex])
                    mySessionDisplay.curScene.setStartPosition(newValue: val!)
                }

            }



        }
    }
}

This function gets called in the following code:

override func prepare(for segue: UIStoryboardSegue, sender: Any?)
{

    if let destination = segue.destination as? SessionDisplayViewControllerTwo
    {
        if let myNames = sender as? [String]
        {
            destination.sessionNames = myNames
            destination.sessionNameIndex = 1
            destination.setStartPosition()
        }
    }
}

Let me know if you need more information. Once again, thanks for your consideration of this matter.

A view controller's views have not yet been loaded in prepareForSegue . As @muescha suggests in his comment, you should set properties in prepareForSegue , and then wait for viewDidLoad or viewWillAppear before you try to install them in your views. I'm not sure why your attempt to manually create your SessionDisplayView is failing, but you should not be trying to create views in prepareForSegue in any case, so the solution is "Don't do that."

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM