Make dialog Async Sync ?

NSAlert same as NSOpenPanel have Style "Sheet" but this way is Asynchronous. Ideally want this to be Synchronous.


For the NSAlert (buttons) I tried using Selector for Target/Action but realised there is no way to pass a Parameter, then wondered if I could get a return result from the func where the Alert is created but no as it's Async. Both the Alert & Open Panel I'm wanting to make as flexable as possible however doing this seems to have it's set-backs.


Any suggestions / methods how to achieve this ?

Replies

When I need to have a sync behavior (I use the result of the NSAlert just after in code), I use 2 patterns:


- put this code in the actions of the buttons

- use semaphore, which is more convenient in some cases.

Thanks. Any chance you can explain a bit more ? I tried using a Semaphore but didn't work for me.

There is another solution which I might stick with. At the moment doesn't matter if it's Sync (runModal) or Async (beginSheetModal) the results just go to the same place whenever they do ...


For the Alert and same will go for OpenPanel, in the function that creates it, I've passed what I'm calling a handler function for the response to be sent to instead of within the Alert itself along with at the moment the SuppressionButton, then deal with accordingly.


let handler = self.someAlertResponse
showMessage(..., handler: handler)

func showMessage(..., handler: @escaping (NSApplication.ModalResponse, Bool) -> ()) {
    ...
    alert.beginSheetModal(for: window!) { (response) in
        handler(response, state)
    ...

func someAlertResponse(_ response: NSApplication.ModalResponse,_ state: Bool) {
    switch response {
    case .alertFirstButtonReturn:
    ...

It is close to what I proposed.


You just put the code in the completion of the alert, not on the completion of each action.


Putting this in the action handler allos to differentiate easily depending on what button you tap.


But you can do this with some test in the alert handler.


For semapohre, it was just to give a larger set of options ; but it is probably overkill here.