当我尝试将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!
答案 0 :(得分:0)
您的问题是您要声明变量eventDetailscontrollers
,如下所示:
var eventDetailscontrollers: EventDetailsController!
但你永远不会给它分配一个值,所以如果你打电话
就是这个原因eventDetailscontrollers.event
这会因eventDetailscontrollers
为nil
而崩溃,因此当时没有成员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)
}