发送到新View Controller的数据为nil,展开可选值

时间:2016-07-22 19:52:42

标签: ios xcode debugging error-handling swift2

当我尝试将Event类的详细信息传递给另一个控制器时,我收到错误消息"fatal error: unexpectedly found nil while unwrapping an Optional value"

这是我的视图控制器,它发送信息:

var eventDetailscontrollers: EventDetailsController!

func showDetailView(event: Events){
    let mainStoryBoarrd: UIStoryboard = UIStoryboard(name:"Main", bundle:nil)
    let detailsViewController: UIViewController = mainStoryBoarrd.instantiateViewControllerWithIdentifier("eventDetailsID")
    eventDetailscontrollers?.event = event //this sends all info as nil
    eventDetailscontrollers.event = event //this causes error

    print(event.name)      // this prints event name fine

    self.presentViewController(detailsViewController, animated: true, completion: nil)
}

这是我将数据发送到的类:

var event: Events!   {
    didSet  {
        eventPriceLabel.text = event!.date //does nothing
    }
}

override func viewDidLoad() {
    super.viewDidLoad()

    let string = event?.name
    print(string)// prints null
}

我的活动课程:

class Events: NSObject {
    var name: String!
    var date: String!
    var address: String!
    var ticketPrice: Int!

2 个答案:

答案 0 :(得分:0)

您的问题是您要声明变量eventDetailscontrollers,如下所示:

var eventDetailscontrollers: EventDetailsController!

但你永远不会给它分配一个值,所以如果你打电话

就是这个原因
eventDetailscontrollers.event

这会因eventDetailscontrollersnil而崩溃,因此当时没有成员event

但是当你打电话时

eventDetailscontrollers?.event

这不会崩溃,因为只有当event不是eventDetailscontrollers时,才会为nil成员分配值,这就是感叹号的含义。 eventDetailscontrollers实际上是nil,因此不会进行任务分配。

因此,您需要先初始化eventDetailscontrollers变量。

我建议你阅读本指南关于optionals,以及关于optional chaining的这个指南

答案 1 :(得分:0)

问题在于:

func showDetailView(event: Events){
    let mainStoryBoarrd: UIStoryboard = UIStoryboard(name:"Main", bundle:nil)
    let detailsViewController: UIViewController = mainStoryBoarrd.instantiateViewControllerWithIdentifier("eventDetailsID")
    eventDetailscontrollers?.event = event //this sends all info as nil
    eventDetailscontrollers.event = event //this causes error

    print(event.name)      // this prints event name fine

    self.presentViewController(detailsViewController, animated: true, completion: nil)
}

您有两个应该相同的变量:

func showDetailView(event: Events){
    let mainStoryBoarrd: UIStoryboard = UIStoryboard(name:"Main", bundle:nil)
    eventDetailscontrollers = mainStoryBoarrd.instantiateViewControllerWithIdentifier("eventDetailsID")
    eventDetailscontrollers?.event = event //this sends all info as nil
    eventDetailscontrollers.event = event //this causes error

    print(event.name)      // this prints event name fine

    self.presentViewController(eventDetailscontrollers, animated: true, completion: nil)
}