0

I'm wanting to call a function and give it parameters using the #selector. However, I get the error:

"Argument of '#selector' does not refer to an '@objc' method, property, or initializer"

@objc func changeCrypto(crypto: String) {
    //stuff
}

func constructMenu() {
    let menu = NSMenu()

    menu.addItem(NSMenuItem(title: "Bitcoin", action: #selector(changeCrypto(crypto: "bitcoin")), keyEquivalent: "B"))
    menu.addItem(NSMenuItem(title: "Ethereum", action: #selector(changeCrypto(crypto: "ethereum")), keyEquivalent: "E"))
    menu.addItem(NSMenuItem(title: "Litecoin", action: #selector(changeCrypto(crypto: "litecoin")), keyEquivalent: "L"))
    menu.addItem(NSMenuItem.separator())
    menu.addItem(NSMenuItem(title: "Quit It", action: #selector(NSApplication.terminate(_:)), keyEquivalent: "q"))

    statusItem.menu = menu
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579
Oskar Sherrah
  • 93
  • 1
  • 10
  • I don't know swift, but I'd guess that it's because you are actually executing `changeCrypto`, so you are passing the *return value* of `changeCrypto` rather than `changeCrypto` itself – JDB Mar 23 '18 at 23:52
  • Post the complete and exact error message in your question. – rmaddy Mar 23 '18 at 23:54
  • @rmaddy That is the complete error message – Oskar Sherrah Mar 23 '18 at 23:57
  • @JDB No, that's not the issue at all. – rmaddy Mar 23 '18 at 23:57
  • You should review [these search results](https://stackoverflow.com/search?q=Argument+of+%27%23selector%27+does+not+refer+to+an+%27%40objc%27+method%2C+property%2C+or+initializer) from the error. – rmaddy Mar 23 '18 at 23:58
  • Possible duplicate of [Argument of '#selector' does not refer to an '@objc' method, property or initializer](https://stackoverflow.com/questions/44493778/argument-of-selector-does-not-refer-to-an-objc-method-property-or-initial) – Willeke Mar 24 '18 at 11:00

1 Answers1

2

I fixed it! I changed it to the following..

@objc func changeCrypto(_ sender: NSMenuItem) {
//Here I call the title of the Menu Item pressed
print(sender.title)
}

func constructMenu() {
let menu = NSMenu()

menu.addItem(NSMenuItem(title: "Bitcoin", action: #selector(changeCrypto(_:)), keyEquivalent: "B"))
menu.addItem(NSMenuItem(title: "Ethereum", action: #selector(changeCrypto(_:)), keyEquivalent: "E"))
menu.addItem(NSMenuItem(title: "Litecoin", action: #selector(changeCrypto(_:)), keyEquivalent: "L"))
menu.addItem(NSMenuItem.separator())
menu.addItem(NSMenuItem(title: "Quit It", action: #selector(NSApplication.terminate(_:)), keyEquivalent: "q"))

statusItem.menu = menu
}
Oskar Sherrah
  • 93
  • 1
  • 10