带有 segue 的 MacOS 应用程序 Class 数据

MacOS Application Class data with segue

我正在使用 Cocoa 和 Swift 3 为 MacOS 开发。当用户单击主菜单上的菜单项时,我正在尝试使用以下代码将用户默认键(布尔值)设置为 true

class app: NSApplication, NSApplicationDelegate {
@IBOutlet weak var connec: NSMenuItem! 
@IBAction func connec(_ sender: Any) { //User has clicked the menu item
    UserDefaults.standard.set(true, forKey: "CalledFromMenu")
    UserDefaults.standard.synchronize() //I know it's deprecated, worth a shot though
    print(UserDefaults.standard.value(forKey: "CalledFromMenu"))
    print("menu")
    //Neither of these actually print when I click the button, but the segue happens.
   //There is a Show segue in the interface builder, I cannot invoke a custom SegueWithIdent here either
   }
}

该应用程序确实执行了 segue,但是 none 的功能。我认为这是因为它首先执行 segue,因此绕过了我的代码,这对我来说最有意义。我想将键设置为 true 并在单击此菜单项时从主菜单 (File>Connection Handler) 中跳出。希望这是有道理的,提前致谢。

您可以将菜单项同步到用户默认值中的布尔值,而不是 IBAction,只需将用户默认值控制器拖到包含菜单栏的场景中,然后绑定 "Value" 绑定您的菜单项到用户默认控制器,在 "Model Key Path" 字段中使用您的默认键。我刚试过这个,即使菜单项也设置为执行 segue,它似乎也能保持值同步。