问候语:Instruments 告诉我 viewDidLoad 中的两个 addLocalMonitor 调用存在内存泄漏(每个 3 字节)。我很高兴看到我的错误以及为什么(可能)泄漏。非常感谢任何帮助!
环境:
- swift :4
- Xcode:9.4
- 部署目标:10.11
代码
override func keyDown(with theEvent: NSEvent) {
nextResponder?.keyDown(with: theEvent)
let hasCommand = theEvent.modifierFlags.contains(.command)
switch theEvent.charactersIgnoringModifiers! {
case "q" where hasCommand == true: // Capture "Command-Q"
let app = NSApplication.shared
app.terminate(NSApplication.shared.delegate as! AppDelegate)
break
default:
break
}
}
override func viewDidLoad() {
super.viewDidLoad()
NSEvent.addLocalMonitorForEvents(matching: .keyDown) { [unowned self] (theEvent) -> NSEvent? in
self.keyDown(with: theEvent)
return theEvent
}
NSEvent.addLocalMonitorForEvents(matching: .flagsChanged) { [unowned self] (theEvent) -> NSEvent? in
self.flagsChanged(with: theEvent)
return theEvent
}
}
最佳答案
像往常一样,对于偶然发现此问题的任何人 - 出现的泄漏通常是其他地方的其他问题的症状。原来我错过了一个埋在别处闭包中的[无主 self ]。一旦解决了这个问题,这个“漏洞”就消失了。针 - 大海捞针。
底线:上面遵循的语法没有错误。
关于swift - NSEvent.addLocalMonitorForEvents 的内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50775982/