swift - 如何将 NSWorkspace 通知迁移到 Swift 4?

标签 swift nsnotifications nsnotification nsworkspace swift4

在 Swift 3 中,我使用以下代码注册了 sleep 和唤醒通知:

let notificationCenter = NSWorkspace.shared.notificationCenter
notificationCenter.addObserver(self, selector: #selector(AppDelegate.sleepListener), name: NSNotification.Name.NSWorkspaceWillSleep, object: nil)
notificationCenter.addObserver(self, selector: #selector(AppDelegate.wakeUpListener), name: NSNotification.Name.NSWorkspaceDidWake, object: nil)

但是在迁移到 Swift 4 之后,我在应用建议的修复后出现了这个错误:

Type 'NSNotification.Name' has no member 'NSWorkspace'

我如何在 Swift 4 中执行此操作?

最佳答案

要解决此问题,您需要将引用通知名称的代码从 NSNotification.Name.NSWorkspaceWillSleep 调整为 NSWorkspace.willSleepNotification。 Swift 4 版本是:

let notificationCenter = NSWorkspace.shared.notificationCenter
notificationCenter.addObserver(self, selector: #selector(AppDelegate.sleepListener), name: NSWorkspace.willSleepNotification, object: nil)
notificationCenter.addObserver(self, selector: #selector(AppDelegate.wakeUpListener), name: NSWorkspace.didWakeNotification, object: nil)

您可以看到此更改的 Apple 的 API 差异 here .

关于swift - 如何将 NSWorkspace 通知迁移到 Swift 4?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44402016/

相关文章:

xcode - 使用未解析的标识符 GGLContext 和 GAI

core-data - 核心数据 : Observing new Entity of certain type

iphone - 使用 NSNotification 在后台线程上执行方法

ios - 为什么当键盘隐藏时整个 View 会跳起来?

ios - RealmSwift : Module Compiled with Swift 3. 0 不能用Swift 3.0.2导入

swift - 在 Swift 中循环播放 A 到 B 的动画

xcode - 选择文本时,OSX NSTextField 会重置 attributeStringValue

ios - 在 View Controller 完全初始化之前调用的 NSNotification

iphone - KVO - 如何获取已注册观察者的对象列表

ios - 从 JSON 加载信息