【问题标题】:Swift: Function call from custom class throws exceptionSwift:来自自定义类的函数调用引发异常
【发布时间】:2015-12-13 12:56:11
【问题描述】:

我有一个 NSButton 的自定义类。按下按钮通过AppDelegate().startTask() 调用主 AppDelegate.swift 中的一个函数,该函数触发一个 NSTask 并通过 AppDelegate.swift 中的 IBOutlet 为 NSProgressIndicator 设置动画。

@IBOutlet weak var mySpinner: NSProgressIndicator!

func startTask() -> Void
{
    mySpinner.startAnimation(true)
    ...
}

它在mySpinner.startAnimation(true) 处抛出一个错误:

致命错误:在展开可选值时意外发现 nil (lldb)

我错过了什么?从自定义类调用时,AppDelegate 是否无权访问此 IBOutlet?从 AppDelegate 中调用此函数可以正常工作。

【问题讨论】:

  • 你应该在viewDidLoad之后调用这个函数,视图还没有加载所以mySpinner是nil
  • 感谢您的解释。 appzYourLife 给出的解决方案是缺少的部分 - 见下文。

标签: swift exception


【解决方案1】:

问题

用这条线

AppDelegate().startTask()

您正在创建一个新的AppDelegate。在这个新实例中,mySpinner 没有被填充,这条线确实崩溃了

mySpinner.startAnimation(true)

因为mySpinndernil

解决方案

您应该检索已创建的 AppDelegate 实例

let appDelegate = NSApplication.sharedApplication().delegate as! AppDelegate
appDelegate.startTask()

【讨论】:

  • 谢谢。这解决了我的问题并很好地解释了它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-05-02
  • 2012-07-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-23
  • 1970-01-01
相关资源
最近更新 更多