-2

I have a class, where most of the logic is handled for clicks and such. There, I made a function that calls another function in a different class. I want to tie this function with NSAlert's button click. However, when I click, I get the error: unrecognized selector sent to instance 0x6000001c50a0. I also have a check if an alert is open and all alerts go through a similar way.

Here's my code:

func goBack()
{
//goback code
}


func showAlert(){
if (!OtherClass.alertCheck)
{
OtherClass.alertCheck = true;
DispatchQueue.main.async(){
var alert = NSAlert()
alert.messageText = "If you want to go back, click back."
var btn = alert.addButton("back")
btn.action = #selector(OtherClass.goBack)
alert.runModal()
OtherClass.alertCheck = false
}
}
}

Even if I don't go through the dispatchQueue, the action is not triggered. I would like to know why in both cases, it doesn't work.

Edged
  • 29
  • 5

2 Answers2

1

The problem is that that is not how you use an NSAlert's buttons. Do not set any action for the button. The button will close the alert, and at that point you can look at what button was clicked and respond accordingly. You do that by capturing the result of runModal, a result which your code ignores. Of course, if this alert has just one button, there is no need to examine anything; just call goBack in the next line.

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • The reason for me trying to add in a selector is that I am trying to make a single Alert object to exist at once to avoid calling two alerts at any time (causing a crash). My idea was to use the alertCheck property to ensure that only 1 alert is open and to pass in the #selector as a parameter so I could make the buttons do different functions depending on the circumstances. goBack is just one of the scenarios. The reason for two alerts opening at the same time could be because the app has some real-time components (http requests),so those could pop up when a user is doing another alert action – Edged Sep 06 '18 at 14:35
0

May be the function "goBack" is called from class OtherClass that try to get some properties from OtherClass that in not created as an object yet ?

Sergey Polozov
  • 225
  • 1
  • 11
  • I tried moving stuff around and it does not help if the function is in the class as well. Also, the OtherClass is Final, so it should be always ready and initialised if I understand what Final means. Lastly, creating a simple button in storyboard and tying that to the GoBack function works. – Edged Sep 05 '18 at 22:11