Thread 1: Fatal error: Unexpecte
2018-07-31 本文已影响1117人
本帅不良
问题:Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value
情形一:通过
let viewController = storyboard.instantiateViewController(withIdentifier: identifier)
得到视图控制器后,我给视图控制器的一个label赋值(通过xib创建)
viewController.detailAddress.text = "XXX"
,是总是出现上述的报错。
解决:将label的赋值放在viewdidload中,不再报错。
分析:可以在viewdidload中赋值,而不能再通过storyboard得到视图控制器时赋值,说明通过storyboard得到的视图控制器并未初始化。
情形二:
block没有实现的时候,会出现这个报错,
//block的声明
var sureBlock : StringBlock!
//block的调用
self.dismiss(animated: true) {
self.sureBlock(dateStr)
}
//block没有使用
//日期选择器(只有月、日)
func selectDatePickerView(presenting presentingViewController: UIViewController, sureActionhandler: ((_ dateStr:String)-> Void)?) -> UIViewController {
let viewController = CommonHelper.instantiateViewControllerWithIdentifier(CommonHelper.kSelectDateVC) as! DatePickViewController
//之前为方便将此代码注释,导致崩溃
// viewController.sureBlock = sureActionhandler
slideInTransitioningDelegate.direction = .bottom
slideInTransitioningDelegate.customHeight = 202
slideInTransitioningDelegate.customWidth = kScreenWidth
slideInTransitioningDelegate.disableCompactHeight = true
DispatchQueue.main.async(execute: {
viewController.transitioningDelegate = self.slideInTransitioningDelegate
viewController.modalPresentationStyle = .custom
presentingViewController.present(viewController, animated: true, completion: nil)
})
return viewController
//
}