Jack44
Jack44

Reputation: 17

Modify stringValue of NSTextField in Swift

I am trying to change the content of NSTextField in the ViewController by changing its stringValue coming from AppDelegate, but it gives me an error.

The code in AppDelegate is:

class AppDelegate: NSObject, NSApplicationDelegate {

    var consoleOutput:String? = "Console Output"

    func executeCommand(command: String, args: [String]) -> String {

        let task = NSTask()
        task.launchPath = command
        task.arguments = args

        let pipe = NSPipe()
        task.standardOutput = pipe
        task.launch()

        let data = pipe.fileHandleForReading.readDataToEndOfFile()
        let output:String = NSString(data: data, encoding: NSUTF8StringEncoding)!
        consoleOutput = output
        return output
    }
}

It is called from the ViewController:

var myDelegate = NSApplication.sharedApplication().delegate! as AppDelegate

and the NSTextField is an IBOutlet created earlier:

@IBOutlet weak var outputText: NSTextField!

and tried to modify later:

outputText.stringValue = myDelegate.consoleOutput!

But all I get is

fatal error: unexpectedly found nil while unwrapping an Optional value

What am I doing wrong?

Upvotes: -1

Views: 1391

Answers (2)

Samaga
Samaga

Reputation: 98

Try setting this line: let output:String = NSString(data: data, encoding: NSUTF8StringEncoding)!to: let output: String = "Test" If this eliminates the error, then you know that NSString(data: data, encoding: NSUTF8StringEncoding) is returning nil, so something is wrong with the data pipe.

Upvotes: 0

nhgrif
nhgrif

Reputation: 62052

consoleOuput is declared as an optional (?) and might have nil in it. Despite this, you are force unwrapping it (!) instead of checking for nil. This is the cause of your "fatal error". Any time you forcibly unwrap an optional, you are risking this error.

You might try something more like this:

outputText.stringValue = myDelegate.consoleOutput ?? ""

This will try to unwrap myDelegate.consoleOutput, but if it can't (because it's nil), it will instead just assign the empty string to outputText.stringValue.

The ?? is known as the "Nil Coalescing Operator".

Upvotes: 1

Related Questions