过去几天我一直坚持这个 -
graphView
是我的UI类实例 - 我在GraphView
类之外声明了我的CalculatorViewDataSource协议,其中包含weak var calcDataSource: CalculatorViewDataSource?
。
在我的GraphViewController中,在graphView出口的didSet {}中,我尝试使用以下代码将委托设置为我假设的现有CalculatorViewController:
if let vc = splitViewController?.viewControllers {
println(vc)
println(vc.count)
if let fst = vc.first {
println(fst.subviews)
println(fst.subviews.first)
}
}
graphView.calcDataSource = splitViewController!.viewControllers.first!.subviews.first as CalculatorViewController
代码编译,但是当我得到graphView.calcDataSource的赋值时,我崩溃了“意外发现了nil”
(输出)
[<UINavigationController: 0x7b71bd10>]
1
nil
fatal error: unexpectedly found nil while unwrapping an Optional value
(故事板)
SplitViewController - NavigationController - (Master) CalculatorViewController
I
NavigationController - (Detail) GraphViewController`
======
我在prepareForSegue内部工作,解决了这个问题 (在按钮上显示故事板segue,名为“Show Graph”)
//CalculatorViewController.swift:
override func prepareForSegue(segue: UIStoryboardSegue?, sender: AnyObject!) {
if (segue!.identifier == "Show Graph") {
var yourNextViewController = (segue!.destinationViewController as UINavigationController)
var detail = yourNextViewController.viewControllers[0] as GraphViewController
var tempview = detail.view // FORCES THE VIEW object into existence, without this it will compile, but next line will crash at runtime (graphView nil)
detail.graphView.calcDataSource = self
}
}
请注意, var tempview = detail.view
在这里至关重要,尽管没有使用。我理解,因为它设置了视图和插座..
答案 0 :(得分:0)
如何(安全地)展开选项:
graphView.calcDataSource = splitViewController!.viewControllers.first!.subviews.first as CalculatorViewController
if let vc = splitViewController?.viewControllers {
println(vc)
if let fst = vc.first {
println(fst.subviews)
println(fst.subviews.first)
}
}