Swift:非零可选值引发零异常 [英] Swift : non-nil optional value raising a nil exception

查看:111
本文介绍了Swift:非零可选值引发零异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一本字典,带有值,我称之为填充字段

I'm having a dictionary, with values, i'm calling it to populate a field

  if let userdata: NSDictionary = self.fbdata {
    println(userdata["email"]) // print Optional(email@domain.com)
    vc.email.text = userdata["email"] as? String ?? "" // raise a nil error
  }

如代码所示,用户数据[email]存在且有一个值,由println打印,无论如何在下一行我有一个nil可选异常引发(甚至默认的值没有使用)

As put in the code, the userdata["email"] exists and has a value, printed by println, anyway at the next line i have a nil optional exception raised (and even the default "" value isn't used)

我看不出我在这里做错了什么

I don't see what i'm doing wrong here

推荐答案


它是文本字段的出口,但它似乎没有打开prepareForSegue函数

it's an outlet to a textfield but it seems to not unwrap in the prepareForSegue function

该评论揭示了你的误解。事情发生在订单中,我在这里讨论: https://stackoverflow.com/a/29552710/341994

That comment reveals your misconception. Things happen in a order, which I discuss here: https://stackoverflow.com/a/29552710/341994

因此,按照设计, prepareForSegue 在新视图控制器具有其视图之前发生 - 或者它的出口。相反,它的出口连接的第一个时刻是它自己的 viewDidLoad ,这是后来的。

So, by design, prepareForSegue happens before the new view controller has its view - or its outlets. Conversely, the first moment when its outlets are connected is its own viewDidLoad, which is later.

你真正的错误但是,更深层次。一个视图控制器具有无业务设置或与另一个视图控制器的插座通信,从而操纵其接口。而是进行设置,以便目标视图控制器具有您可以设置的普通属性。在 viewDidLoad 中,该视图控制器检查该属性,检索该值,并通过其出口设置其自己的接口。

Your real mistake, though, is deeper. One view controller has no business setting or talking to another view controller's outlets and thus manipulating its interface. Instead, set things up so that the destination view controller has an ordinary property which you can set. In viewDidLoad, that view controller than checks that property, retrieves the value, and sets its own interface through its outlet.

所以,总结一下: prepareForSegue 是你初始化新视图控制器的机会。但就是这样。之后,新的视图控制器将控制自己的视图 - 顾名思义!它将从它自己的 viewDidLoad 开始,然后再开始。

So, to sum up: prepareForSegue is your chance to initialize the new view controller. But that's all. The new view controller will then later control its own view — as the name implies! And it will do this starting in its own viewDidLoad and later.

这篇关于Swift:非零可选值引发零异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆