Alert produces app crash

Hello:

I am trying to get my users to provide some information to use in the app by present an alert as the user begins. My code is causing a crash with fatal error Unexpectedly found nil while unwrapping an Optional value (line 13).

    var window: NSWindow?
   
    func checkGroupName() {
        let alert = NSAlert()
        alert.messageText = "Please enter your group name"
        alert.addButton(withTitle: "Save")
        alert.addButton(withTitle: "Cancel")

        let inputTextField = NSTextField(frame: NSRect(x: 0, y: 0, width: 300, height: 24))
        inputTextField.placeholderString = "Enter group name"
        alert.accessoryView = inputTextField

        alert.beginSheetModal(for: self.view.window!, completionHandler: { (modalResponse) -> Void in
            if modalResponse == NSApplication.ModalResponse.alertFirstButtonReturn {
                let enteredString = inputTextField.stringValue
                print("Entered string = \"\(enteredString)\"")
            }
        })
    }


What is causing the error?

Replies

I solved the problem by editing the code as follows:


var window: NSWindow?
   
    func checkGroupName() {
        let alert = NSAlert()
        alert.messageText = "Please enter your group name"
        alert.addButton(withTitle: "Save")
        alert.addButton(withTitle: "Cancel")

        let inputTextField = NSTextField(frame: NSRect(x: 0, y: 0, width: 300, height: 24))
        inputTextField.placeholderString = "Enter group name"
        alert.accessoryView = inputTextField
        alert.runModal()
    }

Great you've found.


You should close the thread on your answer and move the thread to Cocoa forum, more appropriate.