Selector() with parameter in Swift + NSMenuItem

Selector() with parameter in Swift + NSMenuItem

我目前正在尝试将钥匙串中的所有键列为 NSMenuItems,当我单击一个键时,我希望它调用一个带有字符串参数的函数,但是 使用我当前的代码,当我 运行 我的应用程序不仅是我点击的键时,每个键都会被删除。

这是我当前的代码:

NSApplicationMain

class AppDelegate: NSObject, NSApplicationDelegate {

   let menu = NSMenu()
   let internetKeychain = Keychain(server: "example.com", protocolType: .https, authenticationType: .htmlForm)

  func applicationDidFinishLaunching(_ aNotification: Notification) {
    for key in internetKeychain.allKeys() {
        menu.addItem(NSMenuItem(title: " \(key)", action: Selector(deleteKey(key: "\(key)")), keyEquivalent: ""));
    }

    if let button = statusItem.button {
        button.title = ""
        button.target = self }
        statusItem.menu = menu
        NSApp.activate(ignoringOtherApps: true)
  }

  func deleteKey(key: String) -> String {
    do {
        try addInternetPasswordVC().internetKeychain.remove("\(key)")
        print("key: \(key) has been removed")
    } catch let error {
        print("error: \(error)") }
    refreshMenu()
    return key
  }

...
}

我怀疑

目标/操作方法的签名不采用任何参数或传递受影响的项目(在本例中为 NSMenuItem 实例),我怀疑它是否可以 return 任何东西。

menu.addItem(NSMenuItem(title: " \(key)", action: #selector(deleteKey(_:)), keyEquivalent: ""));

...

func deleteKey(_ sender: NSMenuItem) {
    do {
        let key = sender.title.substring(from: sender.title.range(of: " ")!.upperBound)
        try addInternetPasswordVC().internetKeychain.remove("\(key)")
        print("key: \(key) has been removed")
        refreshMenu()
    } catch let error {
        print("error: \(error)") 
    }
}

PS:调用refreshMenu()只有在我猜到钥匙被移除时才有用。