下面这个简单的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 ),但没有效果。
发布于 2017-10-17 03:24:06
在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属性就会继续存在。
https://stackoverflow.com/questions/46781766
复制相似问题