Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
265 views
in Technique[技术] by (71.8m points)

ios - Swift : non-nil optional value raising a nil exception

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 protected])
    vc.email.text = userdata["email"] as? String ?? "" // raise a nil error
  }

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

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.

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...