awado
awado

Reputation: 217

Swift: Function call from custom class throws exception

I have a cusom class for NSButton. Pressing the button calls a function in the main AppDelegate.swift by AppDelegate().startTask(), which fires an NSTask and animates an NSProgressIndicator via IBOutlet in AppDelegate.swift.

@IBOutlet weak var mySpinner: NSProgressIndicator!

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

It throws an error at mySpinner.startAnimation(true):

fatal error: unexpectedly found nil while unwrapping an Optional value (lldb)

What am I missing? Does AppDelegate not have access to this IBOutlet when called from a custom class? Calling this function from within AppDelegate works fine.

Upvotes: 1

Views: 68

Answers (1)

Luca Angeletti
Luca Angeletti

Reputation: 59536

Problem

With this line

AppDelegate().startTask()

you are creating a new AppDelegate. In this new instance mySpinner is not populated and this line does crash

mySpinner.startAnimation(true)

because mySpinnder is nil.

Solution

You should instead retrieve the instance of AppDelegate already created

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

Upvotes: 2

Related Questions