我使用此类抽象 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 错误而崩溃。
但是,当我注释掉设置目标或操作的行时,问题就会消失(当然,菜单将无法单击)。
那么我该如何解决这个问题呢?谢谢。
编辑:
我应该声明我已经尝试过这些事情:
- 使用 #selector(x.doAction) 而不是 #selector(MenuItem.doAction)
- 使用#selector(x.doAction(sender:))
此外,输出窗口中没有任何内容。这就是我在这里寻求帮助的原因。更糟糕的是,它涉及 EXC_BAD_ACCESS ,鉴于内存应该由系统管理,我几乎无法理解这一点。
最佳答案
所以问题是,我传递给静态 getMenu
函数的数组内的 items
在 getMenu 函数完成后(很快就会被释放)随后是 popUpMenuWithEvent:forView
)。
我通过对该数组进行强引用解决了这个问题。
关于swift - 当 NSMenuItem 的目标/选择器设置为对象时 EXC_BAD_ACCESS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51722778/