简体   繁体   English

在swift解开Optional值时意外发现nil

[英]unexpectedly found nil while unwrapping an Optional value in swift

I tried this code 我尝试了这段代码

  let secondView = SecondViewController(nibName: "secondView", bundle: nil)
    secondView.secondViewLabel.text = self.TextBox.text
    navigationController?.pushViewController(secondView, animated: true)

I am trying to pass the value from the text box to a label in the next view controller.But i get an error 我正在尝试将值从文本框传递到下一个视图控制器中的标签。但是我得到一个错误

I also tried copying the text box value to a sting declared in the second View controller that also returns nil. 我还尝试将文本框值复制到第二个View控制器中声明的字符串,该字符串也返回nil。

let secondView = SecondViewController(nibName: "secondView", bundle: nil)
    secondView.toPass = self.TextBox.text
    navigationController?.pushViewController(secondView, animated: true)
    println(secondView.toPass) // i get the string printed here

in second view controller 在第二个视图控制器

      var toPass:String! 

in view did load 鉴于确实加载

    secondLabel.text = toPass
     println(toPass) // i get the string printed nil

help me guys i am new to swift 帮帮我,我是新手

Make the type of toPass a String conditional like so 将toPass的类型设置为条件字符串,如下所示

var toPass: String?

In viewDidLoad, do this : 在viewDidLoad中,执行以下操作:

if let passedString = toPass {
    secondLabel.text = toPass
    println(toPass)
}

Then put a breakpoint inside the if let block to see if toPass ever had a value or it isn't being set at all. 然后在if let块中放置一个断点,以查看toPass是否曾经有一个值或根本没有被设置。 Really need to know what type the TextBox is. 真的需要知道TextBox是什么类型。

[Edit 2] [编辑2]

If the problem is that the value is being set before the viewController secondView has been decoded from a nib, I'd suggest you make a convenience initializer that uses the initWithNib but also takes the extra title string or whatever it is. 如果问题在于该值是在从笔尖将viewController secondView解码之前设置的,则建议您创建一个方便的初始化程序,该初始化程序使用initWithNib,但也可以使用额外的标题字符串或其他内容。 There you can set the value of your textLabel's text to the parameter the new initializer takes. 在那里,您可以将textLabel的文本值设置为新初始化程序采用的参数。 Of course this would mean that you'll have to subclass UIViewController. 当然,这意味着您将必须继承UIViewController。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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