gpt4 book ai didi

Swift 定时器延迟不暂停执行

转载 作者:行者123 更新时间:2023-11-30 13:12:25 24 4
gpt4 key购买 nike

我用 swift 制作了一个计时器,每 0.01 秒更新一次 GUI(未包含在代码中)。在重复调用的代码中,我将其设置为在达到目标时间量时使计时器无效。我期望它在计时器完成之前不会返回主函数,但是当计时器仍在运行时, main() 函数上的命令仍将继续执行。我已将代码压缩为一个小示例,但仍然会产生问题。如果有任何错误或者您想要更多代码,请告诉我。这是代码:

import UIKit

class TimerTestFile: UIViewController {
var dataObject: String = ""

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
main()
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}

override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
}

func updateTime() {

let currentTime = NSDate.timeIntervalSinceReferenceDate()

//Find the difference between current time and start time.

var elapsedTime: NSTimeInterval = currentTime - startTime

//calculate the minutes in elapsed time.

let minutes = UInt8(elapsedTime / 60.0)

elapsedTime -= (NSTimeInterval(minutes) * 60)

//calculate the seconds in elapsed time.

let seconds = UInt8(elapsedTime)

elapsedTime -= NSTimeInterval(seconds)

//find out the fraction of milliseconds to be displayed.

let fraction = UInt8(elapsedTime * 100)

//add the leading zero for minutes, seconds and millseconds and store them as string constants
let strSeconds = String(format: "%02d", (UInt8(targetSeconds) - seconds))

if seconds == UInt8(targetSeconds) {
timer.invalidate()
}

/* --GUI ONLY-- timerLabel.text = strSeconds
let percentNum = (Float(seconds) + Float(fraction) / 100)
print (percentNum)
let percent = Float(percentNum) / Float(targetSeconds)
print(percent)
progressBar.setProgress(Float(percent), animated: true) */

}

func Timer(Seconds: Int) {
progressBar.setProgress(0.0, animated: false)
targetSeconds = Seconds
let aSelector : Selector = #selector(TimerTestFile.updateTime)
timer = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: aSelector, userInfo: nil, repeats: true)
startTime = NSDate.timeIntervalSinceReferenceDate()
}

func main() {
Timer(5)
//This timer is not delayed until the proir is done
Timer(5)
}


}

最佳答案

计算机执行任务的速度比每毫秒(0.01 秒)执行一个命令要快得多。

首先,您安排计时器,该计时器将在 0.01 秒后首先触发。与此同时,执行将返回到之前发生的情况(Timer 方法,然后返回到 main 方法。)当计时器触发时,一旦完成计算机还可以利用另外几微秒在主线程上运行其他代码。

这个故事的寓意是,在计时器未触发的时间间隙中,执行会返回到其他地方。

此外,如果您需要此 GUI 在用户与 UI 交互时仍然更新(例如,当用户滚动或类似操作时),您将需要显式地将 NSTimer 添加到 main使用初始化程序而不是 scheduledTimer 方法创建循环后,使用常见模式运行循环,如所述 here (尽管是在 Objective-C 中)。

旁注:考虑更改您的 Timer 方法。在即将推出的 Foundation 版本中,NSTimer 已在 Swift 中重命名为 Timer,并且您的函数看起来像是一个初始化程序。此外,方法名称和属性在 Swift 中应为小写。

关于Swift 定时器延迟不暂停执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38596960/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com