【发布时间】:2015-07-21 19:17:40
【问题描述】:
过去几天我一直坚持这个 -
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`
- 是语法错误还是赋值错误?
- 我正在尝试从细节委托给 UISplitView 的 masterView,我应该尝试在 masterView 中设置委托吗?这是否假设 detail / graphView 已经存在? (这似乎是 (errors creating a delegate from UISplitViewDetail to master in Swift) 所暗示的)
========
已解决!
我通过在 prepareForSegue 内部工作解决了这个问题 (在名为“Show Graph”的按钮上带有故事板segue)
//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 在这里很关键,尽管没有被使用。我理解它设置视图和出口..
【问题讨论】:
-
解开所有选项,不要使用
!,尤其是在调试时。还要记录您的 splitViewController、第一个 viewController 等,以查看它是否存在或存在多少。打印是你的朋友 -
如何正确记录 VC?用 print() 重载 didLoad()?对于通过 splitViewController 这样的情节提要创建的 VC,我该怎么做?