Why is it that after showing an NSAlert nothing works until I close the NSAlert?
I was trying to print a statement after the display of an NSAlert but print is not working.
Below I have attached my code:
let alert: NSAlert = NSAlert()
alert.messageText = "Hello I am Message text"
alert.informativeText = "i am information"
alert.addButton(withTitle: "OK") // First Button
alert.addButton(withTitle: "Cancel") // 2nd Button
alert.alertStyle = NSAlert.Style.warning
alert.delegate = self
if alert.runModal() == .alertFirstButtonReturn {
print("First Button clicked")
} else {
print("Cancel button clicked")
}
print("after NSAlert >>>>>>> ")

Notice how
runModalreturns the result of the modal as aNSModalResponse. Code after the linealert.runModal()must be able to access the value that it returns, e.g.If the code after
runModalwere run as soon as the modal is displayed, what wouldresultbe? The user has not clicked any buttons on the modal yet, so no one knows!This is why when
runModalis called, code execution kind of just pauses there, at that line, until the user chooses one of the options.runModalis synchronous and blocking.Compare this with
alert.beginSheetModal, which accepts acompletionHandlerclosure, and the modal response is not returned, but passed to thecompletionHandler. This allows the code after the call to continue to run while the modal is presented, because the code after the call does not have access to the modal response. Only the code in thecompletionHandlerdoes.beginSheetModalis asynchronous.If you have something you want to print as soon as the alert is displayed, write it before the
runModalcall, and (optionally) wrap it in aDispatchQueue.asyncAfter/DispatchQueue.asynccall, so that yourprintis asynchronous.