下面的简单Swift 4示例应在计算机显示屏进入休眠状态时停止。
class Observer {
var asleep = false
func addDNC () {
NSWorkspace.shared.notificationCenter.addObserver(forName: NSWorkspace.screensDidSleepNotification, object: nil, queue: nil, using: notificationRecieved)
}
func notificationRecieved (n: Notification) {
asleep = true
}
}
let observer = Observer ()
observer.addDNC ()
while (!observer.asleep) {}
print ("zzzz")
然而,该程序陷入了while循环。我做错了什么,等待通知的正确方法是什么?
我尝试在功能声明中使用选择器(#selector (notificationRecieved)
,@objc
),但无济于事。
答案 0 :(得分:1)
在Xcode中启动模板应用程序并修改ViewController.swift来执行此操作:
import Cocoa
class Observer {
var asleep = false
func addDNC () {
NSWorkspace.shared.notificationCenter.addObserver(forName: NSWorkspace.screensDidSleepNotification, object: nil, queue: nil, using: notificationRecieved)
}
func notificationRecieved (n: Notification) {
print("got sleep notification!")
asleep = true
}
}
class ViewController: NSViewController {
let observer = Observer ()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
observer.addDNC ()
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
}
你的代码和我的代码之间的区别在于我没有做你正在做的古怪的困倦轮询(这会导致旋转的披萨光标),我也设置observer
到是ViewController
对象之外的属性,因此只要视图控制器执行,observer
属性就会保持不变。