Swift:来自自定义类的函数调用抛出异常

时间:2015-12-13 12:56:11

标签: swift exception

我有一个NSButton的cusom类。按下按钮通过AppDelegate().startTask()调用主AppDelegate.swift中的函数,该函数触发NSTask并通过AppDelegate.swift中的IBOutlet激活NSProgressIndicator。

@IBOutlet weak var mySpinner: NSProgressIndicator!

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

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

  

致命错误:在展开Optional值时意外发现nil   (LLDB)

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

1 个答案:

答案 0 :(得分:2)

问题

使用此行

AppDelegate().startTask()

您正在创建新的AppDelegate。在这个新实例中,mySpinner未填充,此行确实崩溃

mySpinner.startAnimation(true)

因为mySpinndernil

解决方案

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

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