Why are my variables empty when I cast them in my iOS application?

故事扮演 提交于 2020-12-15 04:12:13

问题


Hi, I am coding an application on Xcode for IOS and I would like to send a variable to another ViewController. The problem is that when I want to send from the controller called "Step1" to set the label of my second view controller called "Step2". To do this I proceed in this way in "Step 1":

guard let step2 = self.storyboard?.instantiateViewController(withIdentifier: Step2) as? EndConfiguration else
        {
            fatalError("Error when trying to get the reference to the Step 2")
        }

step2.nameLabelOutlet?.text = "Jonh"

But my label is not set... Could someone help me with this problem?

Thank you in advance.


回答1:


EDITED:

There are 3 parts to debugging the problem:

  1. Does the call to instantiateViewController(withIdentifier:) return a viewController? As @aheze points out, you're passing an identifier of EndConfiguration. Unless that is a string constant (e.g. let EndConfiguration = "EndConfiguration") that seems odd. Since you're trying to cast the returned object to type EndConfiguration it seems clear that something isn't right. (EndConfiguration can't be both a view controller class and a string constant.)

    To debug the call to instantiateViewController(withIdentifier:) you should get rid of the cast (the as? EndConfiguration bit) and see if the call returns a view controller.

  2. The second part is the conditional cast (The as? EndConfiguration bit.) If what is created is not a view controller of class EndConfiguration that will fail. It's pretty easy to accidentally leave your view controller's class as the default class UIViewController, and not change it to your custom class in Interface builder. To check that open your storyboard, select the scene for that view controller, select the view controller in that scene, and check in the "identity inspector" that the class is your EndConfiguration class.

  3. As pointed out by PaulW in his comment, a view controller's views are not loaded by the time it's returned in a call to instantiateViewController(withIdentifier:), so your code step2.nameLabelOutlet?.text = "Jonh" won't work because nameLabelOutlet will be nil. Plus, you shouldn't manipulate another view controller's views. Treat them as private. You should add a string property to the target view controller that IT picks up in viewWillAppear and installs in it's view as appropriate.



来源:https://stackoverflow.com/questions/65256352/why-are-my-variables-empty-when-i-cast-them-in-my-ios-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!