swift - 当 NSMenuItem 的目标/选择器设置为对象时 EXC_BAD_ACCESS

标签 swift macos nsmenu nsmenuitem

我使用此类抽象 NSMenuItem:

class MenuItem{
    let title: String
    let iconName: String
    let action: Action
    init(title: String, iconName: String, _ action: @escaping Action) {
        self.title = title
        self.iconName = iconName
        self.action = action
    }

    @objc func doAction(sender: NSMenuItem){
        action()
    }
}

这是构建菜单的静态函数:

static func getMenu(items: [MenuItem]) -> NSMenu{
    let m = NSMenu()
    for x in items{
        let item = NSMenuItem()
        item.title = x.title
        item.target = x // If I remove this line or the line below, there won't be any crash
        item.action = #selector(MenuItem.doAction) 
        item.image = x.iconName.toImage()
        m.addItem(item)
    }

    return m
}

现在我的问题是,每当显示上下文菜单时,程序都会因 EXC_BAD_ACCESS 错误而崩溃。

但是,当我注释掉设置目标或操作的行时,问题就会消失(当然,菜单将无法单击)。

那么我该如何解决这个问题呢?谢谢。

编辑:

我应该声明我已经尝试过这些事情:

  1. 使用 #selector(x.doAction) 而不是 #selector(MenuItem.doAction)
  2. 使用#selector(x.doAction(sender:))

此外,输出窗口中没有任何内容。这就是我在这里寻求帮助的原因。更糟糕的是,它涉及 EXC_BAD_ACCESS ,鉴于内存应该由系统管理,我几乎无法理解这一点。

最佳答案

所以问题是,我传递给静态 getMenu 函数的数组内的 items 在 getMenu 函数完成后(很快就会被释放)随后是 popUpMenuWithEvent:forView)。

我通过对该数组进行强引用解决了这个问题。

关于swift - 当 NSMenuItem 的目标/选择器设置为对象时 EXC_BAD_ACCESS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51722778/

相关文章:

ios - 由于某种原因在 iOS 中托管对象上下文为 nil

swift - 一个 View Controller 中的两个 TableView swift2.0 中带有 didSelectRowAtIndexPath

macos - 如何在 Mac 上的 GitHub Desktop 中重置 Bitbucket 密码?

xcode - applicationDidFinishLaunching 未调用

cocoa NSMenu 在位置添加 NSMenuItem

cocoa - NSMenu 中的 XCode 风格搜索字段?

arrays - 对象数组和 TableView

ios - PDFKit - 使用 pageViewController 的 PDFView - 滑动到下一页时页面呈现缓慢

macos - 如何从另一个应用程序以编程方式移动/调整窗口大小?

cocoa - NSStatusItem 内 WebView 的自定义右键菜单