从 NSTimer 设置时 NSImageView 更新延迟
NSImageView update delayed when set from an NSTimer
我在 Swift 的一个项目中需要严格控制某些部分的图像显示和删除时间。我发现当我从计时器触发的块内设置 NSImageView 的 image
属性 时,屏幕上图像的实际显示最多延迟一秒任务完成。 (这是通过目测并使用秒表测量写入 NSLog 行和图像实际出现在屏幕上之间的时间来测量的。)
无论是通过设置现有 NSImageView 的 image
属性 还是当场构建一个并将其添加为子视图,通过单击触发图像显示似乎都是瞬间发生的。
我试图将行为减少到一个相当简单的测试用例,在视图的基本设置之后(将图像加载到变量中并布置几个目标图像位置,这些位置是 NSImageViews 存储到 targets
array), 设置一个Timer,在其userInfo
属性中存储targets
数组的索引,以触发以下方法:
@objc func testATimer(fromTimer: Timer) {
if let targetLocation = fromTimer.userInfo as? Int {
NSLog("Placing target \(targetLocation)")
targets[targetLocation].image = targetImage
OperationQueue.main.addOperation {
let nextLocation = targetLocation + 1
if (nextLocation < self.targets.count) {
NSLog("Setting timer for target \(nextLocation)")
let _ = Timer.scheduledTimer(timeInterval: 2.0, target: self, selector: #selector(ViewController.testATimer(fromTimer:)), userInfo: nextLocation, repeats: false)
}
}
}
}
观察到的日志条目出现 "Placing target x" 和设置为显示在下一行的图像之间的时间似乎平均在 0.3 到 0.6 秒之间。这远远超出了这个项目可以容忍的延迟,因为图像一次只能在屏幕上显示 1 秒。
关于为什么会发生这种情况,我最好的猜测是它与计时器有关 运行 在与主显示线程不同的线程上;但是,我没有足够的多线程编程经验来确切地知道如何减轻这种情况。
非常感谢任何帮助,如果我遗漏了可以使回答更容易(或可能)的信息,我非常乐意提供。
好吧,在 irc.freenode.net 上的 #macdev 上与一些有帮助的人探讨了这个问题后,我发现问题的根源是每次将图像设置为NSImage 视图。提前减小图像的大小解决了这个问题。 (就像设置图像一次,然后隐藏和显示 NSImageView 一样。)
我在 Swift 的一个项目中需要严格控制某些部分的图像显示和删除时间。我发现当我从计时器触发的块内设置 NSImageView 的 image
属性 时,屏幕上图像的实际显示最多延迟一秒任务完成。 (这是通过目测并使用秒表测量写入 NSLog 行和图像实际出现在屏幕上之间的时间来测量的。)
无论是通过设置现有 NSImageView 的 image
属性 还是当场构建一个并将其添加为子视图,通过单击触发图像显示似乎都是瞬间发生的。
我试图将行为减少到一个相当简单的测试用例,在视图的基本设置之后(将图像加载到变量中并布置几个目标图像位置,这些位置是 NSImageViews 存储到 targets
array), 设置一个Timer,在其userInfo
属性中存储targets
数组的索引,以触发以下方法:
@objc func testATimer(fromTimer: Timer) {
if let targetLocation = fromTimer.userInfo as? Int {
NSLog("Placing target \(targetLocation)")
targets[targetLocation].image = targetImage
OperationQueue.main.addOperation {
let nextLocation = targetLocation + 1
if (nextLocation < self.targets.count) {
NSLog("Setting timer for target \(nextLocation)")
let _ = Timer.scheduledTimer(timeInterval: 2.0, target: self, selector: #selector(ViewController.testATimer(fromTimer:)), userInfo: nextLocation, repeats: false)
}
}
}
}
观察到的日志条目出现 "Placing target x" 和设置为显示在下一行的图像之间的时间似乎平均在 0.3 到 0.6 秒之间。这远远超出了这个项目可以容忍的延迟,因为图像一次只能在屏幕上显示 1 秒。
关于为什么会发生这种情况,我最好的猜测是它与计时器有关 运行 在与主显示线程不同的线程上;但是,我没有足够的多线程编程经验来确切地知道如何减轻这种情况。
非常感谢任何帮助,如果我遗漏了可以使回答更容易(或可能)的信息,我非常乐意提供。
好吧,在 irc.freenode.net 上的 #macdev 上与一些有帮助的人探讨了这个问题后,我发现问题的根源是每次将图像设置为NSImage 视图。提前减小图像的大小解决了这个问题。 (就像设置图像一次,然后隐藏和显示 NSImageView 一样。)