我正在使用这个类抽象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函数完成后,我传递给静态getMenu
函数的数组内的items
被释放(紧随其后的是popUpMenuWithEvent:forView
(。
我通过对该数组的强引用解决了它。