【问题标题】:"unexpectedly found nil" - delegate assignment in subVC“意外发现 nil” - subVC 中的委托分配
【发布时间】: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`

========

已解决!

我通过在 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,我该怎么做?

标签: ios swift delegates


【解决方案1】:

如何(安全地)解开可选项:

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)
    }
}

【讨论】:

  • 假设 if 块在赋值之前(获取输出)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多